locorecto
locorecto

Reputation: 1203

Passing a closure to Jquery $.each

I have the function requestXML which makes an asynchronous call to get a xml file

I also have this implementation which works fine

function show(url){
    requestXML(url, function(xml){
        var items = $(xml).find('item');
        var list = new Array();
        $.each(items, function(){
            list.push($(this).text());
        });
        displayList(list);
    });
}

However, I want to make the function show more generic by doing this

function show(url, func1){
    requestXML(url, function(xml){
        var items = $(xml).find('item');
        var list = new Array();
        $.each(items, func1(list));
        displayList(list);
    });
}

var func1 = function(list){
    list.push($(this).text());
}

When I do this I get the follow error : "Uncaught TypeError: Cannot call method 'call' of undefined". I know the object this from list.push($(this).text()); in func has to be changed to something else but I don't know to what. How can I make this work?

Upvotes: 2

Views: 804

Answers (3)

Paul
Paul

Reputation: 141827

You're calling func1(list) immediately and then passing it's return value (undefined, since it has no return statements) to $.each.

$.each(items, func1(list));

Is equivalent to:

var result = func1(list); // Will be undefined
$.each(items, result);

You could use this instead:

function show(url, func1){
    requestXML(url, function(xml){
        var items = $(xml).find('item');
        var list = new Array();
        $.each(items, $.proxy(func1, list));
        displayList(list);
    });
}

var func1 = function(el){
    this.push($(el).text());
}

Upvotes: 5

Anand Jha
Anand Jha

Reputation: 10724

Try this...

function show(url, func1){
    var list = [];
    var func1 = function(ele){
          list.push($(ele).text());
    }

    requestXML(url, function(xml){
        var items = $(xml).find('item');
        $.each(items, func1(ele));
        displayList(list);
        });
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You need something like

function show(url, func1){
    requestXML(url, function(xml){
        var items = $(xml).find('item');
        var list = new Array();
        $.each(items, function(idx, value){
            func1.call(this, list, idx, value)
        });
        displayList(list);
    });
}

var func1 = function(list, idx, value){
    list.push($(this).text());
}

Upvotes: 2

Related Questions