[英]Binding a callback to this in Backbone.js
This is probably pretty simple, but for the life of me I can't figure out why this isn't binding correctly. 这可能很简单,但对于我的生活,我无法弄清楚为什么这不正确绑定。
In my main view: 在我的主要观点中:
initMap: function() {
forge.logging.log('... Initializing map');
var createMap = function(position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude, true);
var options = {
zoom: 15,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById('map_canvas'), options);
this.addMarkers();
};
_.bind(createMap, this);
forge.geolocation.getCurrentPosition(createMap);
forge.logging.log('Created map ...');
},
addMarkers: function() {
alert('addMarkers');
forge.logging.log('... Adding markers');
var tempData = ["xxxxxxxx",
"xxxxxxx",
"xxxxxxxx"];
_.each(tempData, function(addr){
google.maps.Geocoder.geocode({'address': addr}, function(res, status){
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
map: this.map,
position: res[0].geometry.location
});
}
});
});
forge.logging.log('Added markers ...');
}
For some reason, the this.addMarkers() doesn't seem to be called. 出于某种原因,似乎没有调用this.addMarkers()。 I'm guessing it's because this isn't bound correctly. 我猜它是因为这没有正确绑定。 The map shows up perfectly fine however. 然而,地图显示完全正常。
How should I bind this to my createMap callback function? 我应该如何将它绑定到我的createMap回调函数?
From the fine manual : 从精细手册 :
bind
_.bind(function, object, [*arguments])
bind_.bind(function, object, [*arguments])
Bind a function to an object , meaning that whenever the function is called, the value of this will be the object . 结合的功能的对象 ,这意味着无论何时调用该函数时, 这个值将是的对象 。 Optionally, bind arguments to the function to pre-fill them, also known as partial application . (可选)将参数绑定到函数以预填充它们,也称为部分应用程序 。
var func = function(greeting){ return greeting + ': ' + this.name }; func = _.bind(func, {name : 'moe'}, 'hi'); func(); => 'hi: moe'
The documentation could be a little more explicit but the important bit is in the example: 文档可能更明确一些,但重要的是在示例中:
func = _.bind(func, ...)
So _.bind
returns the bound function, it doesn't modify the function in-place. 所以_.bind
返回绑定函数,它不会就地修改函数。 You want to say this: 你想这样说:
createMap = _.bind(createMap, this);
or maybe this: 或者这个:
var createMap = function(position) { ... };
forge.geolocation.getCurrentPosition(_.bind(this, createMap));
Perhaps you're confused by using _.bindAll
in other places. 也许你在其他地方使用_.bindAll
感到困惑。 The _.bindAll
function looks like it modifies the functions in-place but it is really modifying the object
in place so this: _.bindAll
函数看起来像就地修改了函数,但实际上是在修改object
所以这样:
_.bindAll(obj, 'm1', 'm2');
is, more or less, doing this internally: 或多或少,在内部这样做:
obj.m1 = _.bind(obj, obj.m1);
obj.m2 = _.bind(obj, obj.m2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.