Why does my simple event handling example not work?

Posted by njreed on Stack Overflow See other posts from Stack Overflow or by njreed
Published on 2011-11-23T09:46:58Z Indexed on 2011/11/23 9:50 UTC
Read the original article Hit count: 173

Filed under:
|

I am trying to make a simple event handler.

(Note, I'm not trying to implement a full-blown publish/subscribe model; I'm just interested in why my example doesn't work as I think it should)

var myObj = (function () {

  var private = "X";

  function triggerEvent(eventName) {
    if (this[eventName]) {
      this[eventName]();
    }
  }

  // Setter / Getter
  function getProp() {
    return private;
  }

  function setProp(value) {
    private = value;
    triggerEvent("onPropChange");
  }

  // Public API
  return {
    // Events
    "onPropChange": null,    // Fires when prop value is changed

    // Methods
    "getProp": getProp,
    "setProp": setProp
  };
})();

// Now set event handler
myObj.onPropChange = function () {
  alert("You changed the property!");
};

myObj.setProp("Z");  // --> Nothing happens. Wrong
                     // Why doesn't my alert show?

I set the onPropChange property of my object to a simpler handler function but it is not being fired. I have debugged this and it seems that in triggerEvent the variable this is referencing the global window object. I thought it should reference myObj (which is what I need).

Can someone explain the error in my thinking and how I correct this? Help much appreciated.

jsFiddle here

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about scope