box86rowh
box86rowh

Reputation: 3415

How can I use getscript from insidea jquery widget

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.

Upvotes: 0

Views: 56

Answers (2)

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

Upvotes: 2

B W
B W

Reputation: 712

What about:

var widget = $.widget(
    ...
    _create: function() {
        $.getScript("URL", function() {
            widget.doSomething();
        });
    },
    doSomething: function() {
        alert("something");
    }
});

Upvotes: 0

Related Questions