0

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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

What about:

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

1 Comment

I think that will cause issues if I have more than 1 instance on the page, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.