我正在使用 fabric.js 在 Canvas 上绘制一些文本。我有一个创建文本标签的功能。我想让标签在被选中时运行一个函数。它的语法是 label.on('selected', functionToCall());
当我将函数设为匿名内部函数时,这很好用,但是当我将它分解为一个单独的函数时,我得到一个未捕获的类型错误:
Cannot read property 'hasOwnProperty' of undefined.
我做错了什么?
下面是对我不起作用的代码。这是 broken code在 jsfiddle 上,一个版本设置了 anonymous function哪个有效。
"use strict";
var canvas = new fabric.Canvas('c', {selection: false}),
position = 50;
function onLabelSelection(theLabel) {
if (theLabel.hasOwnProperty('edge')) {
selectedEdge = theLabel.edge;
} else {
selectedEdge = null;
}
}
function createLabel() {
var label;
label = new fabric.Text('Hello World', {
left: position,
top: position
});
position += 50;
label.edge = null;
label.on('selected', onLabelSelection(this));
return label;
}
canvas.on('mouse:up', function() {
var newLabel = createLabel();
canvas.add(newLabel);
});
最佳答案
The syntax for this is
label.on('selected', functionToCall())
没有。事件处理程序的语法是传递处理函数,而不是调用它:
label.on('selected', functionToCall);
您可能想尝试 label.on('selected', onLabelSelection.bind(this))
或 - 因为 this
在 createLablel
中显然 undefined
- 只是 label.on('selected', onLabelSelection)
。
关于javascript - 未捕获的类型错误 : Cannot read property 'hasOwnProperty' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23610476/