题
我有一个骨干模型 line
其中包含模型的集合 Stop
。在某个时候,我想使用下划线函数迭代线路的停靠点,并沿着线路沿线获取总旅行时间 reduce
.
但是,这行不通。似乎在某个时候发生了一些事情。它似乎只包含一个没有有意义属性的对象,尽管我知道它已经被带有有效属性的四个定格模型所填充。
该模型:
App.models.Line = Backbone.Model.extend({
initialize: function() {
var stops = new App.models.Stops({
model: App.models.Stop,
id: this.get("id")
});
stops.fetch();
this.set({
stops: stops
});
this.set({unique: true});
this.calculateTotalTime();
},
calculateTotalTime: function() {
this.get("stops").each(function(num) {
console.log("Model!");
});
console.log("Unique: ", this.get("unique"));
}
});
控制台打印输出是:
Model!
Unique: true
应该有四个“模型!”,因为模型的数量为四个。
最奇怪的是,一切在控制台中都很好:
window.line.get("stops").each(function(num) {
console.log("Model!");
});
Model!
Model!
Model!
Model!
JS用链轮编译:
//= require ./init
//= require ./lib/jquery
//= require ./lib/underscore
//= require ./lib/backbone
//= require ./lib/raphael
//= require_tree ./controllers
//= require_tree ./models
//= require_tree ./views
//= require ./main
init.js:
window.App = {};
App.views = [];
App.models = [];
main.js:
$(function() {
window.line = new App.models.Line({name: "4", id: 4});
window.lineView = new App.views.Line({model: line});
$("#outer").append(lineView.render().el);
});
其他一些奇怪的行为:
console.log(this.get("stops"))
在模型中产生了这个相当正常的对象:
child
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
id: 4
length: 4
models: Array[4]
0: Backbone.Model
1: Backbone.Model
2: Backbone.Model
3: Backbone.Model
length: 4
__proto__: Array[0]
__proto__: ctor
但是打电话 console.log(this.get("stops").models)
, ,应该产生数组,仅返回此对象的数组,没有有用的属性:
[
Backbone.Model
_callbacks: Object
_changed: false
_changing: false
_escapedAttributes: Object
_previousAttributes: Object
attributes: Object
id: 4
model: function (){ return parent.apply(this, arguments); }
__proto__: Object
cid: "c1"
id: 4
__proto__: Object
]
我怀疑这一切都归结为对的性质 this
. 。很高兴提供任何帮助。
解决方案
stops.fetch()
是一个异步过程,因此您在获取结果从服务器返回之前可能会发射后立即编写的代码。
提取后,您需要修改代码以运行所有内容。最简单的方法是与 reset
来自 stops
收藏:
App.models.Line = Backbone.Model.extend({
initialize: function() {
var stops = new App.models.Stops({
model: App.models.Stop,
id: this.get("id")
});
// store the stops, and then bind to the event
this.set({stops: stops});
stops.bind("reset", this.stopsLoaded, this);
stops.fetch();
},
stopsLoaded: function(){
// get the stops, now that the collection has been populated
var stops = this.get("stops");
this.set({unique: true});
this.calculateTotalTime();
},
calculateTotalTime: function() {
this.get("stops").each(function(num) {
console.log("Model!");
});
console.log("Unique: ", this.get("unique"));
}
});
它在您的控制台中工作的原因是因为到输入代码以评估模型的停止时, fetch
呼叫已经返回并填充了该集合。
希望有帮助
不隶属于 StackOverflow