Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined

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);
});
like image 601
WhiteHotLoveTiger Avatar asked May 12 '14 13:05

WhiteHotLoveTiger


People also ask

What is cannot read property of undefined in JavaScript?

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.

What is the meaning of undefined in JavaScript?

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.

Why can’t I call a function on an undefined variable?

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.


Video Answer


1 Answers

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).

like image 141
Bergi Avatar answered Oct 02 '22 12:10

Bergi