防止在fabric.js调用的函数中进行延迟评估 [英] Preventing lazy evaluation in function called by fabric.js

查看:65
本文介绍了防止在fabric.js调用的函数中进行延迟评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案为如何向特定对象而非画布上的所有对象添加链接"(实际上是重定向到URL的事件)提供了有益的说明:

This answer gives a helpful explication of how to add a "link" (really, an event that redirects to a URL) to a particular object rather than to all objects on the canvas:

如何将URL添加到Fabric中的图像.js?

但是,当放置在生成多个对象的循环中时,它仅链接到创建的最后一个对象的值.

However, when placed inside a loop that generates multiple objects, it only links to the last object created's value.

这是一个例子:

for (var p = 0; p<2; p++) {
  var object = new fabric.Circle({ radius: 10, top: 10 + 20 * p, left: 10 });
  object.on('selected', function() {
    window.location.href = "mylink" + "/" + p;
  })
  canvas.add(object);
}

当我要的是第一个对象链接到"mylink/0",第二个对象链接到"mylink/1"时,这两个对象都链接到"mylink/1".

This will have both objects linking to "mylink/1", when what I want is for the first object to link to "mylink/0" and the second to link to "mylink/1".

我的Java技术技能停留在1999年,但是对我来说,这似乎是个懒惰的加载问题.如何强制从每个循环创建的对象具有自己的功能?

My Javascript skills are stuck in 1999, but this looks like a lazy loading problem to me. How do I force the object created from each loop to have its own function?

推荐答案

这似乎与延迟评估/关闭有关.

It does appear to be about lazy evaluation/closures.

使用这个漂亮的答案( JavaScript:在For循环中创建函数),我能够制定解决方案.希望在这里发布对其他人有用.请参阅链接的答案以了解其工作原理.

Using this beautiful answer (Javascript: Creating Functions in a For Loop), I was able to craft a solution. Posting here in the hopes it will be useful to others. See the linked answer for why it works.

  var fxnArr = [];
  for( var p = 0; p < rows.length; p++ ) {
    fxnArr[fxnArr.length] = (function(val) { return function(){  
        window.location.href = "mylink" + "/" + val; 
    } })(p);
  }
  for (var p = 0; p<2; p++) {
    var object = new fabric.Circle({ radius: 10, top: 10 + 20 * p, left: 10 });
    object.on('selected', fxnArr[p] );
    canvas.add(object);
  }

这篇关于防止在fabric.js调用的函数中进行延迟评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆