这可能非常简单,但我一直想不通为什么绑定(bind)不正确。
在我的主要观点中:
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 ...');
}
出于某种原因,this.addMarkers() 似乎没有被调用。我猜这是因为没有正确绑定(bind)。然而, map 显示得非常好。
我应该如何将它绑定(bind)到我的 createMap 回调函数?
最佳答案
来自fine manual :
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'
文档可能更明确一点,但重要的是在示例中:
func = _.bind(func, ...)
所以 _.bind
返回绑定(bind)函数,它不会就地修改函数。你想这样说:
createMap = _.bind(createMap, this);
或者可能是这样:
var createMap = function(position) { ... };
forge.geolocation.getCurrentPosition(_.bind(this, createMap));
也许您对在其他地方使用 _.bindAll
感到困惑。 _.bindAll
函数看起来像是就地修改了函数,但它实际上是就地修改了 object
因此:
_.bindAll(obj, 'm1', 'm2');
或多或少是在内部这样做:
obj.m1 = _.bind(obj, obj.m1);
obj.m2 = _.bind(obj, obj.m2);
关于javascript - 在 Backbone.js 中绑定(bind)一个回调到这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206267/