Shlomi Schwartz
Shlomi Schwartz

Reputation: 8913

JavaScript binding for AJAX calls

I'm trying to bind the AJAX callback function to a certain scope, what am I doing wrong?

here is my code:

var MainApp = {
    files:{
        "A":{
            url:"files/a.json",
            content:""
        },
        "B":{
            url:"files/b.json",
            content:""
        }
    },
    init:function () {
        this.loadFiles();
    },
    loadFiles:function () {
        for (var i in this.files) {
            var f = function (data) {
                console.log("callback",this);
            };
            console.log("binding",this);
            f.bind(this);
            $.get(this.files[i].url, f);
        }
    }
};

$(function () {
    MainApp.init();
});

Upvotes: 1

Views: 166

Answers (2)

bobince
bobince

Reputation: 536587

f.bind(this);

Function#bind doesn't alter the original function, it returns a new function bound to the parameter. You probably meant:

f= f.bind(this);

Upvotes: 1

Jivings
Jivings

Reputation: 23260

Try using call:

that = this;
$.get(this.files[i].url, function() {
   f.call(that)
});

Upvotes: 0

Related Questions