I have a new jquery UI widget factory widget, in the create method I want to load a js file and then do stuff with it. However when I call $.getScript and refer to "this" within the call back "this" is no longer my plugin instance, it is relating now to the loaded script! How can I access the plugin instance instead?
CODE:
$.widget("custom.embed", {
options:{
base_url: "",
theme_url: "",
widget_base_url: "",
token: ""
},
_create: function () {
$.getScript("URL", function(){
this.doSomething();
});
},
doSomething: function(){
alert("something");
}
});
Thank you!
EDIT
$.widget("custom.embed", {
options:{
base_url: "",
theme_url: "",
widget_base_url: "",
token: ""
},
_create: function () {
var widget = this;
$.getScript("URL", function(){
widget.doSomething();
});
},
doSomething: function(){
alert("something");
}
});
Is this a safe approach? It seems to work.
Your problem is related to closures(variable scope depending on function definition). I'll do something like:
_create: function() {
var self = this;
$.getScript("URL", function() {
self.doSomething();
});
Read this article