Search code examples
javascriptmethodsprototypekineticjs

Reference prototype method from one object to another JavaScript (KineticJS)


I try to create method in KineticJS. I added this code:

Kinetic.Circle.prototype.test = function(){
  alert(1);
}

And it's working, but i'm tring to add this method not for only Circle but for layers and more. So i tried with this code

Kinetic.Node.prototype.test = function(){
  alert(1);
}

And i have error in my console: Uncaught TypeError: Object # has no method 'test'.

I tried to search some solution in Google but i can't find it.

@EDITED For Bergi :) I have array with layers where in layers[layer_name].object i'm creating Kinetic.Layer object like code below:

layers.names[name]={
  id:variable,
  object:new Kinetic.Layer()
};
stage.add(layers.names[name].object);

Yes, stage is created before in this code:

var stage=new Kinetic.Stage({
  container:'canvas',
  draggable:true,
  height:document.documentElement.clientHeight,
  width:document.documentElement.clientWidth
});

After that i'm adding point to my object in array:

var point=new Kinetic.Circle({
  fill:'#000',
  radius:3,
  x:parent.children('input[name="x"]').val(),
  y:parent.children('input[name="y"]').val()
});
var layer_name=$('input[name="layer"]').val();
layers.names[layer_name].object.add(point).draw();

And at this moment i'm tring to run my method:

var layer_name=$('input[name="layer"]').val();
var point=layers.names[layer_name].object.children[$('input[name="element_index"]').val()];
point.test();

But in console i have only error which i paste before.


Solution

  • It looks like Kinetic doesn't handle inheritance like you're expecting it to. Kinetic.Node is not actually in the prototype chain of Kinetic.Circle.

    When Kinetic.Circle is created there is a utility function that simply copies all of the functions from Kinetic.Node.prototype to Kinetic.Circle.prototype.

    I'm not a Kinetic user, but I think something like this might work.

    var myMethods = {
        test: function() {
            alert(1);
        }
    }
    
    Kinetic.Util.addMethods(Kinetic.Circle, myMethods);
    Kinetic.Util.addMethods(Kinetic.Shape, myMethods);
    Kinetic.Util.addMethods(Kinetic.Node, myMethods);
    Kinetic.Util.addMethods(Kinetic.Layer, myMethods);
    

    Not nearly as clean as simply adding a method to the super's prototype, but I'm sure they have their reasons for doing things this way.