javascriptjquerycallbackjquery-ui-widget-factoryevent-triggers

Triggers as Callbacks in jQuery UI Widgets


I am working on my first jQuery UI Widget. It uses $.ajax to pull data then populates elements after the data is loaded. Normally I would have a function that does the ajax pull and pass an "onSuccess" callback function to that function to be executed when the ajax pull was successful.

Here is a really simplified version of what I mean:

function doAjax(onSuccess) {
    $.ajax({
        success: function (data) {
            onSuccess(data);
        }
    });
}

doAjax(function (data) {console.log(data);});

With the widget factory, I know that I can add a trigger in the $.ajax's on success function. Can I use that trigger inside my widgets code?

Something like this works but doesn't seem like it would be the best practice:

_create: function() {
    self.options.dataLoaded = function (e, data) {console.log(data);};
    this._doAjax();
},
_doAjax: function() {
    var self = this;

    $.ajax({
        success: function (data) {
            self._trigger('dataLoaded', null, data);
        }
    });
}

What is considered best practice here?


Solution

  • From doing some trial and error code I've determined that the first options is the best. Here is a simplified version of the code that seems to work best.

    _create: function() {
        var self = this;
        self._doAjax(self.doStuff);
    },
    _doAjax: function(onSuccess) {
        var self = this;
    
        $.ajax({
            context: self,
            success: function (data) {
                onSuccess.call(this, data);
                self._trigger('dataLoaded', null, data);
            }
        });
    },
    doStuff: function(data) {
        var self = this;
    
        console.log(self);
        console.log(data);
    }
    

    This allows me to use a callback like I normally would and allows the user of my widget to use the dataLoaded event if it is needed. The $.ajax content: option coupled with onSuccess.call(this,data) allows me to ensure this will still refer to my widget from inside the doStuff method that was used as the onSuccess callback.