Blacklabel
Blacklabel

Reputation: 846

Ajax call overwrites $(this) object in widget factory

Widget Code :

    (function($){

        $.widget("demo.widget", {

            _create: function() {
            },

            _init: function() {
            },

            load: function(){
                var widget = this;
                $.post(
                    Url, 
                    ajaxUtils.success(function(json) {
                    //variable widget is overwritten here if I create multiple instances of the widget

                    alert(widget.element.data("name"));
                    }), "json");

            },

            setOptions: function(name) {
                $(this).data("name", name);
            }

    })(jQuery);

I create Multiple instances of the same widget.

    $('<div/>').widget();
    $('<div/>').data('widget').setOptions("Name1");
    $('<div/>').data('widget').load();

    $('<div/>').widget();
    $('<div/>').data('widget').setOptions("Name2");
    $('<div/>').data('widget').load(); 

But the widget variable in the ajax success call always returns Name2. How should I write the code to store instance specific data?

Upvotes: 0

Views: 489

Answers (1)

Kevin B
Kevin B

Reputation: 95022

this in the context of var widget = this is the plugin object, not the element that the plugin was initialized on.

This:

alert(widget.data("name"));

should be:

alert(widget.element.data("name"));

Edit: I don't know what's going on with the ajaxUtils object and its success method, is it returning a function that gets called on the $.post success?

Upvotes: 1

Related Questions