2

I ran into this code and am not sure how it works:

options.on('change', this._onBundleOptionChanged.bind(this));

this._onBundleOptionChanged is simply a function that takes one paramter, event:

_onBundleOptionChanged: function onBundleOptionChanged(event) {

jQuery version is 1.12.4.

the bind call returns function bound() whatever that means and if bind is passed a single parameter it has to be an object the documentation says "An object containing one or more DOM event types and functions to execute for them." here: http://api.jquery.com/bind/

So as I understand what it accomplishes, calling the _onBundleOptionChanged method when a select dropdown is changed.

What I don't understand is how, or why anyone would program it this way.

  • 2
    It depends more on the code around `options.on("change")`. Using `bind(this)` will make `this` mean the same thing inside `onBundleOptionChanged` as it does outside it (where the event handler is assigned). There could be lots of reasons for doing this, as well as it simply being unnecessary. Have a look how `this` is used inside the event handler - it should give you some clue as to why. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind – Reinstate Monica Cellio Dec 22 '17 at 09:04
  • Isn't bind a deprecated use of on that just references on? Or is there another method called bind other than the jquery one? this points to the object that _onBundleOptionChanged belongs to. –  Dec 22 '17 at 09:06

1 Answers1

2

It is not jQuery's bind.

It is function.prototype.bind (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind).

It is changing the context of the callback function to the be the same as when this statement is executed. This can be very useful.

In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).

See:

How to access the correct `this` inside a callback?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

squgeim
  • 2,321
  • 1
  • 14
  • 21