PLui
PLui

Reputation: 765

Recursive Asynchronous Callbacks in Javascript

In relation to this question, I'm trying to add a callback to get the data back. So I tried this:

var subgroupIds = [];
var that = this;
this.getSubGroups = function (groupId,callback) {
    var anotherObject = this;
    this.getGroups("groupId="+groupId, function(groups) {
        if ($.isEmptyObject(groups)) {
            return;
        } else {
            $.each(groups, function(index,group) {
                subgroupIds.push(group.id);
                that.getSubGroups(group.id);
            });
            anotherObject.callback(group.id);
        }
     });
}

I thought I have a better understanding of closure after the previous question but I guess I don't...I'm getting the following error:

Uncaught TypeError: Object [object Window] has no method 'callback'

What am I doing wrong here?

Edit

Here's the content of getGroups:

this.getGroups = function(filter,callback,error_callback) {
    this.getJSON('/'+apiVersion+'/groups/',function(data){
        // run through the filter engine
        output = runFilter(data, filter);
        callback(output);
    },error_callback);
}

Upvotes: 0

Views: 1740

Answers (2)

Nikita Tkachenko
Nikita Tkachenko

Reputation: 2146

It doesn't need to be anotherObject.callback(group.id);, what you need is callback(group.id);

It looks like you're confusing this with arguments object.

arguments holds all parameters that are passed into the function:

var aFunction = function () {
    for (var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
};

aFunction(1, 2, 3, 4); // 1, 2, 3, 4

While this basically refers to the "owner" of the function (which is, roughly speaking, whatever happens to be before the dot):

var aFunction = function () {
    console.log(this);
};

var object1 = { f: aFunction, name: "object1" };
var object2 = { f: aFunction, name: "object2" };

object1.f(); // Object { name="object1", f=function()}
object2.f(); // Object { name="object2", f=function()}
aFunction(); // Window

Upvotes: 1

Augustin Riedinger
Augustin Riedinger

Reputation: 22208

The callback is a parameter, it is not bound to the context.

I think what you want is to call the callback with anotherObject as the this value, right ?

You can achieve that with :

$.proxy(callback, anotherObject)(group.id);

Or if you only want to execute the callback, and you want to use closure, you need to add :

this.callback = callback; //before
var anotherObject = this;

Upvotes: 0

Related Questions