javascript - jQuery.proxy() usage -


I was reading about API, it looks promising but I was wondering what is the best use of this situation . When there is a function in which is this then can someone illuminate me?

This is just a built-in example of the situation where it can be useful to assume that a person is an object in which the name of the property is also linked to a text input element , And whenever there is a change in the input value, the name also updates in this person's object.

  function person (l) {this.name = ''; $ (L) .change (function) {// person wants to update this name of the object, but this is not because it refers to element // here that triggered the change event .}); }  

A solution that we use often is to store this reference in a variable and use it inside the callback function:

  function Person l) {this.name = ''; Var self = this; // store reference for this $ (L) .change (function (event) {self.name = this.value; // captures itself in a closure}); }  

Alternatively, we could use the jQuery.proxy here, so the reference to refers to the purpose of that person The element that triggers the event.

  function person (l) {this.name = ''; $ (L) .change (jQuery.proxy (function) {this.name = event.target.value;}, this)); }  

Note that this feature has been standardized in ECMAScript 5, which includes borrowed method from now and is already available on some browsers.

  function person l) {this.name = ''; $ (L) .change (function (event) {this.name = event.target.value;} .bind (this)); // we are binding the function in person's object}  

Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -