0

This doesn't work, but gives you the idea: a widget needs to use its own method as a callbacK:

$.widget("me.mywidget", {

    _create: function() {
        this.call("mymodule", "myaction", {arg: this.options.value}, _parseData);
    },

    _parseData: function(data) {
        console.log(data);
    },

    call: function(module, action, params, callback) {
        var params = params || {};
        var url = "/" + module + "/"  + action;

        $.post(url, params, function(data) {
            if (data.payload) callback(data.payload);
        });
    },
});

It currently throws the exception: Uncaught ReferenceError: _parseData is not defined

What's the canonical way of doing this?

Wells
  • 8,895
  • 10
  • 45
  • 75

1 Answers1

0

The $.post callback needs to call your own callback using .apply or .call, both of which allow you to set what the scope of this is in the function you call.

call: function(module, action, params, callback) {
    var params = params || {};
    var url = "/" + module + "/"  + action;
    var self = this;

    $.post(url, params, function(data) {
        if (data.payload) callback.apply(self, [ data.payload ]);
    });
},

Or:

call: function(module, action, params, callback) {
    var params = params || {};
    var url = "/" + module + "/"  + action;

    $.post(url, params, function(data) {
        if (data.payload) callbac.call(self, data.payload);
    });
},

You can read this for more information on apply/call.

Community
  • 1
  • 1
Langdon
  • 19,288
  • 17
  • 84
  • 106