Reputation: 598
I'm writing a jQuery plugin. It should fetch data from a JSON API and put the result in a specified place. Due to this, I am using $.getJSON
to get the JSON required.
In $.getJSON
's callback, I am trying to output the data in the specified place using .html()
. When I open a demo, nothing is outputted, and Chrome Devtools says that 'undefined is not a function'.
Here is my code:
;(function($, window, document, undefined) {
$.fn.hipsum = function(options) {
...
var data = $.getJSON(url, function(data){
this.html(data);
});
};
})(jQuery, window, document);
Can someone explain why this is not working?
Upvotes: 0
Views: 100
Reputation: 750
As @kJ Price answered, when you reach a callback the context changes, and this no longer reefers to the first object, but to the ajax call. Just store the object before the call and use it when needed.
Upvotes: 1
Reputation: 5964
"this" no longer represents the jQuery object once the callback method gets hit. You need to reference the "this" object outside of the scope of the callback and then use it again inside the method as example with "self" below.
;(function($, window, document, undefined) {
$.fn.hipsum = function(options) {
var self = this;
var data = $.getJSON(url, function(data){
self.html(data);
});
};
})(jQuery, window, document);
Upvotes: 2