Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined

40,592

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

Share:
40,592
WhiteHotLoveTiger
Author by

WhiteHotLoveTiger

Human who tries to program computers.

Updated on April 28, 2021

Comments

  • WhiteHotLoveTiger
    WhiteHotLoveTiger about 3 years

    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);
    });