我想要的是使用 this.plotPort(); 从plotLoc 调用plotPort但我无法...但是如果我使用 self.plotPort();它不适用于 IE。 我的解决方法是在重置时向 lLoca 添加事件以调用plotPort。 为什么 this.plotPort 不起作用?
var Loca = Backbone.Model.extend({latitude:{},longitude:{}});
var LocaList = Backbone.Collection.extend({
model : Loca,
url : "/getLatLongList"
});
var PortList = Backbone.Collection.extend({
model : Loca,
url : "/getLatLongListForPort"
});
var lLoca = new LocaList;
var lPort = new PortList;
var CreateMap = Backbone.View.extend({
el : 'div',
map : {},
latitude : {},
longitude : {},
initialize : function() {
var lOptions = {};
lOptions.success = this.plotLoc;
lLoca.fetch(lOptions,this);
lLoca.on('reset',this.plotPort(),this);
//_.bindAll(this,'plotPort');
},
plotLoc : function() {
// var test =lLoca.toJSON();
// $('#pchart').html(JSON.stringify(lLoca));
this.latitude = lLoca.toJSON()[0].latitude;
this.longitude = lLoca.toJSON()[0].longitude;
this.latlng = new google.maps.LatLng(this.latitude,
this.longitude);
var mapOptions = {
center : this.latlng,
zoom : 15,
mapTypeId : google.maps.MapTypeId.SATELLITE,
mapTypeControl : false,
streetViewControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
}
};
mapContainer = $("#mapContainer").get(0);
this.map = new google.maps.Map(mapContainer, mapOptions);
_.each(lLoca.models, function(loc) {
var marker = new google.maps.Marker({
position : new google.maps.LatLng(
loc.toJSON().latitude,
loc.toJSON().longitude),
map : this.map,
title : ""
});
}, this);
lLoca.reset();
//console.log(self+"");
//this.plotPort();
},
plotPort : function() {
lPort.fetch({
success: function() {
var postImage = new google.maps.MarkerImage(
"Images/greenflag.png",
new google.maps.Size(50, 50));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(
lPort.toJSON()[0].latitude,
lPort.toJSON()[0].longitude),
map : this.map,
icon : postImage,
title : "From"
});
marker = new google.maps.Marker({
position : new google.maps.LatLng(
lPort.toJSON()[1].latitude,
lPort.toJSON()[1].longitude),
map : this.map,
icon : postImage,
title : "To"
});
}
});
},
render : function() {
return this;
}
});
var App = new CreateMap;
最佳答案
我从你的代码中可以理解,你应该在执行 fetch
之前绑定(bind) reset
并且绑定(bind)不正确,它应该是这样的,
lLoca.on('reset', this.plotPort, this); // notice () being removed after this.plotPort
lLoca.fetch(lOptions, this);
这会将 reset
与该方法绑定(bind),而不是调用它。
关于从另一个方法调用一个方法,它非常简单,我们只需使用 this
来调用它,但如果该调用是从某个回调函数或任何其他类似的东西进行的,其中 this
不引用 View ,那么建议在回调之前保存对 this
的引用,并在回调中需要时使用它。例如,
var _view = this;
// doing collection fetch
this.collection.fetch({
success : function (collection, response) {
// if you want to access view here, it can be accessed using
// '_view' variable, because 'this' here does not point to the view.
}
});
这只是一个示例,但相同的概念可以用于类似的问题。
关于javascript - 在主干 View 中从另一个函数调用一个函数 Backbone.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13194944/