0

I am trying to call an IIFE from within a constructor and it doesn't seem to run when I initialize the object. Here's my code:

function TitleView(el) {
  this.el = el;
  this.parent = el.parentNode;
  this.events = {
    'onclick' : function() {
      console.log('title view onclick');
    }
  };
  (function addEventHandlers() {

    for (var ev in this.events) {
      if (this.events.hasOwnProperty(ev)) {
        this.el[ev] = this.events[ev];
        console.log('abc');
      }
    }
  }());
}


var titleView = new TitleView(document.getElementById('task-title-h1'));

My aim here is to attach a bunch of event handlers on object initialization. If I remove the IIFE and keep the body of the code, the event handler is attached to titleView.el, but with the IIFE, it's null. Why is this the case? (This is pure javascript, btw, not a framework.)

foundling
  • 1,695
  • 1
  • 16
  • 22
  • 3
    It does run, but `this` is not what you think it is. Btw, what's the reason to use an IEFE here in the first place? – Bergi Jul 26 '15 at 20:35
  • The duplicate is a bit off but I think it solves your problem and answers your questions. If not, please comment. – Bergi Jul 26 '15 at 20:37
  • @Bergi, Thanks for pointing me to that question. I wanted to put this in a function and not just leave it freely sitting at the end of the constructor to make it more readable (giving it the name addEventHandlers) and the only way I could see of doing this was putting it in an IIFE. Maybe it's excessive, though. In any case, I got it working by passing `this` into the call method of the IIFE. – foundling Jul 26 '15 at 20:56
  • You'll want to have a look at [Using Named Immediately-Invoked Function Expression (IIFE) instead of comments](http://stackoverflow.com/q/15530374/1048572) then :-) – Bergi Jul 26 '15 at 21:30

0 Answers0