views:

1514

answers:

6

Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this

function MyObject() {
  this.doSomething = function() {
    ...
  }

  var self = this
  $('#foobar').bind('click', function(){
    self.doSomethng()
    // this.doSomething() would not work here
  })
}

It works, but is that the best way to do it? It looks strange to me.

A: 

I think it's actually depends on what are you going to do inside your doDomething function. If you going to access MyObject properties using this keyword then you have to use that. But I think that following code fragment will also work if you are not doing any special things using object(MyObject) properties.

function doSomething(){ ......... }

$("#foobar").ready('click', function(){

});

+4  A: 

Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.

It's something that took me a little while to really get, it does look odd at first.

I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):

function MyObject(){
  var me = this;

  //Events
  Click = onClick; //Allows user to override onClick event with their own

  //Event Handlers
  onClick = function(args){
    me.MyProperty = args; //Reference me, referencing this refers to onClick
    ...
    //Do other stuff
  }
}
BenAlabaster
+2  A: 

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.

neonski
A: 

yep, it's quite a lifesaver (or better, a 'sanitysaver'). of course, i got downvoted for claiming that it's one of the blunders of bad language design in JS

Javier
I can't believe you thought you could knock the language design of JS and get away with it :oP JS coders are fanatics.
BenAlabaster
as seen on some lists: "JavaScript is Scheme done wrong"
Javier
+12  A: 
Eugene Lazutkin
+3  A: 

A good article which explains those little issues in javascript is this one:

http://www.alistapart.com/articles/getoutbindingsituations

Hope this helps.

Jaime Febres
a very good article
Cheeso