いくつかのコードをリストし、状況を説明します。
(1)をインスタンス化しApp.views.tasks
ます。このビューのinitialize
関数で、タスクをフェッチします。
(2)関数から、各タスクrender
のインスタンスを作成します。(3)の関数では、 をインスタンス化し、それにコメントのコレクションと、タスクがレンダリングされる要素への参照を渡します。(4)タスクのコメントの取得を開始します。 App.views.task
initialize
App.views.task
App.views.comments
DOM
App.views.comments
質問:に渡す要素
への参照は、コメントによって引き起こされる遅延がなかった場合になります。関数で参照を
渡した場合、すべて問題ありませんが、呼び出されるたびにインスタンス化されることも意味します。これは問題ありません。したがって、これはそれを行うための幸運な方法にすぎません。
何が起こるかを説明するコメントをいくつか追加しました。それらはとにあります。 DOM
App.views.comments
undefined
fetching
el
render
App.views.comments
render
fetching
undefined
App.views.task
App.views.comments
場合によってはこれを解決する最善の方法は何ですか?
App.collections.Tasks = Backbone.Collection.extend({
model: App.models.Task,
url: App.baseHrefReq + '/tasks/all'
});
App.models.Task = Backbone.Model.extend({
initialize: function() {
this.set({comments: new App.collections.taskComments});
this.get('comments').url = App.baseHrefReq + '/comments/get/task-id/' + this.get('id');
}
});
App.views.tasks = Backbone.View.extend({
initialize: function() {
App.iCollections.Tasks = new App.collections.Tasks;
App.iCollections.Tasks.bind('reset', this.render, this);
App.iCollections.Tasks.bind('add', this.renderTask, this);
App.iCollections.Tasks.fetch();
},
render: function() {
$('.feed-list').html('');
App.iCollections.Tasks.each(this.renderTask);
},
renderTask: function(task) {
var view = new App.views.task({model: task});
$('.feed-list').append(view.render().el);
}
});
App.iViews.tasks = new App.views.tasks;
App.views.task = Backbone.View.extend({
tagName: 'li',
template: _.template($('#task-item-template').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
this.model.get('comments').bind('reset', this.render, this);
this.model.get('comments').bind('add', this.render, this);
this.model.get('comments').bind('remove', this.render, this);
//I pass the DOM reference here
this.commentsView = new App.views.comments({collection: this.model.get('comments'), el: this.$el});
},
render: function() {
var modelJSON = this.model.toJSON();
//the DOM reference is only ready and defined here
this.$el.html(this.template(modelJSON));
return this;
}
});
App.views.comments = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'renderComment');
this.collection.bind('reset', this.render, this);
this.collection.bind('add', this.renderComment, this);
this.collection.bind('remove', this.remove, this);
this.collection.fetch();
},
render: function() {
//if there wasn't the fetch() above, $el would be undefined at this point
this.$el.find('.feed-comments ul').html('');
this.collection.each(this.renderComment);
},
renderComment: function(comment) {
var view = new App.views.comment({model: comment});
this.$el.find('.feed-comments ul').append(view.render().el);
}
});
});
App.views.comment = Backbone.View.extend({...})