I am very new to jquery and javascript. I am looking at how Splunk implements some of its modules and got confused.
Here is sample code with a lot of stuff left out.
this.input.bind("focus",this.onInputFocus.bind(this))
this.input refers to a textbox used for a SearchBar. Later, in the file, onInputFocus is declared
onInputFocus: function(evt) {
...
...
return true
},
I know the “this.input.bind” statement tells the browser to execute onInputFocus when a person clicks in the textbox but I do not understand .bind(this) at the end of the eventhandler. Please explain to me this notation so I understand what is happening.
The “outer”
bindis binding an event handler to thefocusevent using jQuery.The “inner”
Function.bindis creating a function that is bound to a particular context (makingthisequal to that context when the function is called). This does not require a framework (but does require a modern browser).So, in this case, the call to
Function.bindis making sure that every timeinputis focused, theonInputFocusmethod’s context is set to the current value ofthis(which is probably the widget/component you’re using). This is necessary because it usually would be the element the event occurred on.The MDN article on
Function.bindhas a good explanation of this.To better illustrate how this works, take a simple example:
HTML:
JavaScript:
In the first event binding,
fillis called andthisis set to#test(since that was the element that was clicked).In the second,
fillis called again, butthisis set to#targetbecause of the call toFunction.bindinside of the event binding.Example: http://jsfiddle.net/GK7L8/