0

I see this works in below code only in init function and functions called within init (e.g.: onSearchClick). Can anyone explain why this is not working in onSearchClick? And what this pattern is called as?

(function() {
    var e,
    Search = {
        ele: {
            sb : $('.searchSubmit'),
            st : $('.searchText')
        },
        vars: {
            debug: true
        },
        init : function() {
            e = this.ele;
            this.addEvents();
        },
        addEvents : function() {
            this.ele.sb.bind('click', this.onSearchClick);
            //Search.ele.sb.bind('click', this.onSearchClick);
            //Both, this. and Search. work
        },
        onSearchClick : function() {
            Search.log('onSearchClick:  - ');
            //this.log('onSearchClick:  - ');
            //Only Search. works, this. not
        },
        log : function(p_sMessage) {
            if(!Search.vars.debug) { return; }
            else { if(window.console) { console.log(p_sMessage); }}
        }
    };
    window.Search = Search;
    window.e = e;
}());
Search.init();
Kunj
  • 1,980
  • 2
  • 22
  • 34
  • 2
    FYI, there is is no need to use an IIFE if you are making the only two variables inside of it global anyway. – Felix Kling Oct 10 '14 at 05:05
  • *"And what is this pattern of JavaScript called?"* The design pattern is often called an IIFE, or Immediately Invoked Function Expression, though there are other names for it. See http://stackoverflow.com/questions/10984652/javascript-immediately-invoked-function-patterns – Paul Oct 10 '14 at 05:07
  • Hi @FelixKling , thanks for you response. I will add all elements of DOM in `ele` variable further. – Kunj Oct 10 '14 at 05:10
  • You can bind `this` context with `this.ele.sb.bind('click', this.onSearchClick.bind(this));` – Vicky Gonsalves Oct 10 '14 at 05:12
  • `this` is special in JS, and has various uses. From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this :"When a function is used as an event handler, its `this` is set to the element the event fired from ...". This behaviour is overriding how you are trying to use `this` and therefore creates an issue. – Paul Oct 10 '14 at 05:19
  • Hi @VickyGonsalves thanks for reply. It executes once on init now, not on click later :( – Kunj Oct 10 '14 at 05:30
  • Thanks @Paul ! You got my problem exactly. Here `this` is the button by which this function is executing. I will have to define `this` in a var. Can you please give me a hint on which level, I should put it? – Kunj Oct 10 '14 at 10:12

0 Answers0