Why does my simple event handling example not work?
- by njreed
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