[英]Accessing Backbone view this from a nested function call
我正在嘗試執行以下操作:
Backbone.View.extend({
...
onEachFeature: function (feature, layer) {
// "this" should be the view but is
// the function like normally in closures
this.doSomething();
},
geoJsonSynced: function () {
this.geojson = L.geoJson(
this.collection.geojson(),
{
onEachFeature: this.onEachFeature
}
);
}
...
});
我認為情況會有所不同,因為onEachFeature是視圖的屬性,但顯然情況並非如此。 我想不出一種正確執行此操作的方法。 通常,對於閉包,我只是執行var that = this,但是在這種情況下,我無法將“ that”納入范圍。
我試圖通過以下方法將其納入范圍:
geoJsonSynced: function () {
var that = this;
this.geojson = L.geoJson(
this.collection.geojson(),
{
onEachFeature: this.onEachFeature
}
);
}
我想我做錯了。
當前,我以非常糟糕的方式(通過我自己的觀點)通過擁有全局變量並在onEachFeature中執行以下操作來做到這一點:
onEachFeature: function (feature, layer) {
var view = globalVariable.someView;
view.doSomething();
}
有一個更好的方法嗎?
編輯:比我想象的要容易修復:
geoJsonSynced: function () {
var onEachFeature = _.bind(this.onEachFeature, this);
this.geojson = L.geoJson(
this.collection.geojson(),
{
onEachFeature: onEachFeature
}
);
}
謝謝代碼運行器。
嘗試使用_.bindall()
, 這里非常清楚地討論了相同的問題
這是使用jQuery執行相同操作的方法
geoJsonSynced: function () {
this.geojson = L.geoJson(
this.collection.geojson(),
{
onEachFeature: $.proxy(this.onEachFeature,this)
}
);
}
文件-http: //api.jquery.com/jquery.proxy/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.