Understanding the 'this' scope in jQuery in a change event

I wrote a quick custom extension for jQuery for the project I'm working on. I find it hard to understand the scope of 'this' in the onChange custom method that I would like to implement. If you leave in the middle of my code where I call the webservice, but if you check the last two methods, you will see where my problem is. I want to call the updateDetails method with the selected value change. However, when this method is called inside the onchange event, I obviously lose the scope of "this" since this.materialListResponse is returned as undefined in this context. Any help helping me figure this out would be greatly appreciated.

$.fn.appendMaterials = function (options) { this.options = options; //Set Default Options this.defaults = { typeID: '66E1320D-51F9-4900-BE84-6D5B571F9B80' }; this.options = $.extend({}, this.defaults, options); // Code here to call web service and generate response XML // this.materialListResponse = $.xml2json( $.parseXML($(this.materialListWebservice()).find("GetMaterialTreeResponse").text())).Materials.Material; this.appendOptionString = function () { var i = 0; this.optionString = '<option>' for (i = 0; i < this.materialListResponse.length; i++) { this.optionString += '<option>' + this.materialListResponse[i].MaterialCode + '</option>'; }; this.append(this.optionString); return this; }; this.appendOptionString(); this.updateDetails = function () { for (i = 0; i < this.materialListResponse.length; i++) { if (this.materialListResponse[i].MaterialCode === this.val()) { $('#table1 #MaterialDescription').val(this.materialListResponse[i].Description); } } } this.change(this.updateDetails) }; 
+4
source share
3 answers

pass this object as data for the event:

 this.change({that: this}, this.updateDetails) 

and then you can access that in the event callback area

 this.updateDetails = function(event) { var that = event.data.that; ... } 

Resources

+5
source

An event handler will be called later when you exit the extension. It is called in the scope of the element, so this will be the changed element.

Copy the link to the list to a local variable and use it in the event handler:

 var list = this.materialListResponse; this.updateDetails = function() { for (i = 0; i < list.length; i++) { if (list[i].MaterialCode === this.val()) { $('#table1 #MaterialDescription').val(list[i].Description); } } } 

Using a local variable in a function, the variable will be part of the closure for this function, so it will survive in the extension method area where it is declared.

+1
source

When a method is called in JavaScript as a callback, it behaves like a function. In this case, β€œthis” refers to the owner of this function, usually the Window object in a web browser.

+1
source

All Articles