質問
バックボーンモデルがあります line
モデルのコレクションが含まれています Stop
。ある時点で、アンダースコア関数を使用して、ラインの停留所を繰り返し、ラインに沿って合計移動時間を取得したいと思います。 reduce
.
ただし、これは機能しません。ある時点でコレクションで何かが起こるようです。意味のある属性のないオブジェクトは1つだけ含まれているようですが、有効な属性を備えた4つのストップモデルが入力されているという事実を知っています。
モデル:
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
モデルの数は4つあるため、4つの「モデル!」が必要です。
最も奇妙なことは、すべてがコンソールでうまく機能することです:
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
コールはすでに返され、コレクションに入力されています。
それが役立つことを願っています