简体   繁体   中英

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();
});
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);

Try using call:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM