Can an event handler be defined in the javascript object's private access itself?

I know I could do this with closure (var self = this) if the object was a function ...

<a href="#" id="x">click here</a> <script type="text/javascript"> var object = { y : 1, handle_click : function (e) { alert('handling click'); //want to access y here return false; }, load : function () { document.getElementById('x').onclick = this.handle_click; } }; object.load(); </script> 
+6
javascript javascript-events event-handling
source share
4 answers

So, the part of the event handler dries just fine (I tested it myself), but, as your comment indicates, you do not have access to the "y" property of the object that you just defined.

It works:

 var object = { y : 1, handle_click : function (e) { alert('handling click'); //want to access y here alert(this.y); return false; }, load : function () { var that = this; document.getElementById('x').onclick = function(e) { that.handle_click(e); // pass-through the event object }; } }; object.load(); 

There are other ways to do this, but it works.

+3
source share

The easiest way to bind a call to handle_click to the object that he defined would be something like this:

  var self=this; document.getElementById('x').onclick = function(e) { return self.handle_click(e) }; 

If you need to pass parameters or want the code to look cleaner (for example, if you configure many similar event handlers), you can use the currying technique to achieve the same:

 bind : function(fn) { var self = this; // copy arguments into local array var args = Array.prototype.slice.call(arguments, 0); // returned function replaces first argument with event arg, // calls fn with composite arguments return function(e) { args[0] = e; return fn.apply(self, args); }; }, 

...

  document.getElementById('x').onclick = this.bind(this.handle_click, "this parameter is passed to handle_click()", "as is this one"); 
+3
source share

I see how to do this with the latter. Any way to do this without an anonymous function?

0
source share

We can directly pass the object using the handler method thanks to AddEventListener, and you will have access to its attributes: http://www.thecssninja.com/javascript/handleevent

I hope this helps those who, like me, will be looking for this topic a few years later!

0
source share

All Articles