我正在使用fabric.js在画布上绘制一些文本.我有一个创建文本标签的功能.我想让标签在选中时运行一个功能.这个的语法是label.on('selected', functionToCall());
当我使函数成为一个匿名的内部函数时这很好用,但当我把它作为一个单独的函数分解时,我得到一个未捕获的TypeError : Cannot read property 'hasOwnProperty' of undefined
. 我究竟做错了什么?
以下代码对我不起作用.这是jsfiddle 上的破解代码,以及使用匿名函数设置的版本.
"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); });
Bergi.. 7
这个的语法是
label.on('selected', functionToCall())
否.事件处理程序的语法是传递处理函数,而不是调用它:
label.on('selected', functionToCall);
您可能想尝试label.on('selected', onLabelSelection.bind(this))
或 - 因为this
内部createLablel
显然undefined
- 只是label.on('selected', onLabelSelection)
.