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(); 
7
  • 2
    FYI, there is is no need to use an IIFE if you are making the only two variables inside of it global anyway. Commented Oct 10, 2014 at 5: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 stackoverflow.com/questions/10984652/… Commented Oct 10, 2014 at 5:07
  • Hi @FelixKling , thanks for you response. I will add all elements of DOM in ele variable further. Commented Oct 10, 2014 at 5:10
  • You can bind this context with this.ele.sb.bind('click', this.onSearchClick.bind(this)); Commented Oct 10, 2014 at 5:12
  • this is special in JS, and has various uses. From developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… :"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. Commented Oct 10, 2014 at 5:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.