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);
});
The TypeError: Cannot read property of undefined is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable. TypeError: Cannot read properties of undefined (reading x) Undefined means that a variable has been declared but has not been assigned a value.
Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.
In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.
The 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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With