I'm using fabric.js to draw some text on a canvas. I have a function to create a text label. I'd like to have labels run a function when they're selected. The syntax for this is label.on('selected', functionToCall());
This works fine when I make the function an anonymous inner function, but when I break it out as a separate function, I get an Uncaught TypeError:
Cannot read property 'hasOwnProperty' of undefined.
What am I doing wrong?
Below is the code which doesn't work for me. Here's the broken code on jsfiddle, and a version set up with an anonymous function which works.
"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);
});
I'm using fabric.js to draw some text on a canvas. I have a function to create a text label. I'd like to have labels run a function when they're selected. The syntax for this is label.on('selected', functionToCall());
This works fine when I make the function an anonymous inner function, but when I break it out as a separate function, I get an Uncaught TypeError:
Cannot read property 'hasOwnProperty' of undefined.
What am I doing wrong?
Below is the code which doesn't work for me. Here's the broken code on jsfiddle, and a version set up with an anonymous function which works.
"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);
});
Share
Improve this question
edited Apr 27, 2021 at 20:20
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked May 12, 2014 at 13:32
WhiteHotLoveTigerWhiteHotLoveTiger
2,2284 gold badges31 silver badges41 bronze badges
1 Answer
Reset to default 10The syntax for this is
label.on('selected', functionToCall())
No. The syntax for event handlers is to pass the handler function, not to call it:
label.on('selected', functionToCall);
You might want to try label.on('selected', onLabelSelection.bind(this))
or - since this
inside createLablel
is apparently undefined
- just label.on('selected', onLabelSelection)
.