2012-10-20 30 views
0

我在使用'this'關鍵字時遇到了一些問題。我明白爲什麼下面不工作,但無法弄清楚如何解決它......使用原型模式在ajax回調中訪問'this'

//Namespace 
var CPT = CPT || {}; 

//Constructor 
CPT.Grid = function (hostElement, surlWeb) { 
    this.hostElement = hostElement; 
    this.surlWeb = surlWeb; 
} 

//Prototype 
CPT.Grid.prototype = { 

    init: function() { 

    $.ajax({ 
     url: this.surlWeb, 
     headers: { "accept": "application/json" }, 
     success: this.showItems 
    }); 
    }, 

    showItems: function (data) { 
    //do some work 

    // this is the error... no access to hostElement because 'this' is the AJAX call 
    this.hostElement.html(items.join('')); 
    } 
} 

function getProducts() { 
    var grid = new CPT.Grid($("#displayDiv"), someUrl); 
    grid.init(); 
} 

我知道我可以沒有一個獨立的showItems功能可能解決這個問題,但我想看看如何做另一種方式。理想情況下,我想將當前對象的引用傳遞給成功處理程序,但無法弄清楚如何做到這一點...

+0

在進入ajax調用之前,您可以簡單地將'this'賦值給其他變量,然後在該變量上調用您的方法。常見的方法是'var self = this; self.my_method_name'。或者您可以使用'.ajax()'調用的上下文字段並傳遞'this' –

回答

5

這是什麼$.ajaxcontext選項是:

$.ajax({ 
    // ... 
    context: this, 
    success: this.showItems 
}); 

這將確保當前(正確)this傳遞到showItems

+0

完美...謝謝! –

1

您正在傳遞函數引用。這將不會有相同的上下文。

...

var self = this; 
$.ajax({ 
     url: this.surlWeb, 
     headers: { "accept": "application/json" }, 
     success: function(){self.showItems.apply(self, arguments) 
    }); 
    }, 

或者

可以上下文綁定到你的方法

this.showItems = this.showItems.bind(this); // will not work IE < 9 
$.ajax({ 
      url: this.surlWeb, 
      headers: { "accept": "application/json" }, 
      success: this.showItems 
     }); 
     },