Search code examples
javascriptprototypejs

JavaScript "this" references the wrong object within an event handler


I'm writing some MVC JavaScript code using Prototype. The problem is that when I reference this in the snippet below it does of course reference the Window object, whereas I need it to refer to my Controller instance so it can invoke my updateValue function, passing the HTML element ID.

I think I have to use bind or bindAsEventListener but I don't really understand how.

var Foo = {
  Controller: Class.create({
    observeEvents: function() {
      $$("#myform input").each(function(input) {
        input.observe("blur", this.updateValue(input.id); // <- wrong this!
      });
    },

    updateValue: function(elementID) {
      ...
    }
  })
}

Any help would be much appreciated.


Solution

  • This should work.

        observeEvents: function() {
          var Controller = this;
          $$("#myform input").each(function(input) {
            input.observe("blur", Controller.updateValue.bind(Controller, input.id));
          });
         ...
    

    If you don't ever want to learn how to use bind (and frankly I don't blame you) then you can forget about it and just use another teensy closure.

        observeEvents: function() {
          var Controller = this;
          $$("#myform input").each(function(input) {
            input.observe("blur", function(event) {
                                    Controller.updateValue(input.id);
                                  });
          });
         ...