Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching functions on an instance of an element

We can modify a DOM element and add to its prototype. For example, if we want to add something only to the canvas, we'd do something like this:

HTMLCanvasElement.prototype.doSomething = function(arg) { ... };

We can then perform this action on a canvas element:

var canvas = document.getElementById('canvasId');
canvas.doSomething(...);

Is it possible to add/attach a function to this instance of the canvas without modifying the prototype of HTMLCanvasElement. I only want a canvas where doSomething(...) was called to have access to the additional methods, not all canvas elements in the DOM. How can I do this?

I've tried the following in my doSomething function:

this.prototype.foobar = function() {...}

However, prototype is undefined here.

like image 300
Sai Avatar asked Sep 29 '12 21:09

Sai


4 Answers

Shusl helped me come up with the correct answer. It was easier than I thought. In my doSomething(args) function, instead of trying to modify the object prototype, I just directly attached the function. Here's the full source code:

HTMLCanvasElement.prototype.doSomething = function(args) {
    this.foobar = function(args) { ... };
}

var canvas = document.getElementById('canvasId');
canvas.doSomething(...);
canvas.foobar(...);

Now, foobar is only accessible to the instance of the canvas where doSomething was called. At the same time, I don't have to have any information about the instance.

like image 157
Sai Avatar answered Sep 21 '22 18:09

Sai


In that case you can directly attache a method to your canvas object

var canvas = document.getElementById('canvasId');
canvas.doSomething= function() {...}; ///doSomething will only be available to this particular canvas.
canvas.doSomething(...);
like image 45
Anoop Avatar answered Sep 24 '22 18:09

Anoop


With jQuery, you can use the data property.

//setting the function
$('element').data('doSomething', function(arg) { ... });
//calling the function
$('element').data('doSomething')(arg);

JSFiddle

like image 27
Austin Brunkhorst Avatar answered Sep 24 '22 18:09

Austin Brunkhorst


Object.defineProperty(element, 'doSomething', {value:function(arg){ ... }} );

Where 'element' is the element you want to add the property to, 'doSomething' is the name and the third argument is an object of the property its self. In your case a function.

For example:

var mycanvas = document.createElement("canvas");

Object.defineProperty(mycanvas, 'doSomething', {
  value: function(x){console.log(x); },
  configurable: true 
});

mycanvas.doSomething('my message');
//prints 'my message' to the console.

The 'configurable' property specifies if you would like the 'doSomething' property to be able to be changed again after it is created. Check out the MDN Details for more information and examples.

like image 36
Josh Haughton Avatar answered Sep 24 '22 18:09

Josh Haughton