Javascript - 如何在对象文字的ajax调用中绑定'this' [英] Javascript - how to bind 'this' inside an ajax call to the object literal

查看:68
本文介绍了Javascript - 如何在对象文字的ajax调用中绑定'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象文字路由器,包含一个ajax调用。我想在ajax调用中调用其他函数 this.printMovies()但是这个引用ajax对象。 / p>

如何逃避它并使这个参考路由器对象本身?

  var router = {

// ...
init:function(){
this.getData(api / movies,movies,callback);
},
getData:function(url,htmlType,callback){
$ .ajax({
url:url,
dataType:'json',
成功:函数(响应){
if(response&& response.length> 0){
this.printMovies(response,callback); //'this'指的是ajax
this.printMovies(响应,回调).bind(this)//仍然不起作用
}
},
错误:function(response){console.log(错误:+响应);}
});
},
printMovies:function(){

},
}


解决方案

context 选项传递给ajax:

  $。ajax({
context:this,
/ * other options * /
}

现在在ajax回调中,这个将引用 router object。


I have an object literal router, containing an ajax call. I want to call other functions this.printMovies() inside the ajax call but this refer to the ajax object.

How do I escape it and make this refer to the router object itself?

var router = {  

    //...
    init : function() {
        this.getData("api/movies", "movies", callback);
    },
    getData : function (url, htmlType, callback) {
        $.ajax({
            url: url,
            dataType: 'json',
            success: function (response) {
                if (response && response.length > 0) {
                    this.printMovies(response, callback); //'this' refers to ajax
                    this.printMovies(response, callback).bind(this) //still doesn't work
                }
            },
            error: function (response) { console.log("Error:" + response); }
        });
    },
    printMovies : function(){

    },  
}

解决方案

Pass context option to ajax:

$.ajax({
  context: this,
  /* other options */
}

Now inside ajax callbacks, this will refer to router object.

这篇关于Javascript - 如何在对象文字的ajax调用中绑定'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆