私は問題がスコープに関係していると信じています。私はjs初心者です。私は小さなbackbone.jsの例を持っています。私がしようとしているのは、サーバからフェッチされたアイテムのリストをプリントアウトすることです。Backbone.jsを使用したスコープエラー?
$(function(){
// = Models =
// Video
window.Video = Backbone.Model.extend({
defaults: function() {
return {
title: 'No title',
description: 'No description'
};
},
urlRoot: 'api/v1/video/'
});
// VideoList Collection
// To be extended for Asset Manager and Search later...
window.VideoList = Backbone.Collection.extend({
model: Video,
url: 'api/v1/video/'
});
// = Views =
window.VideoListView = Backbone.View.extend({
tagName: 'ul',
render: function(eventName) {
$(this.el).html("");
_.each(this.model.models, function(video) {
$(this.el).append(new VideoListRowView({model:video}).render().el);
}, this);
return this;
}
});
// VideoRow
window.VideoListRowView = Backbone.View.extend({
tagName: "li",
template: _.template("id: <%= id %>; title: <%= title %>"),
className: "asset-video-row",
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes:{
"":"assetManager"
},
assetManager:function() {
this.assetList = new VideoList();
this.assetListView = new VideoListView({model:this.assetList});
this.assetList.fetch();
$('#content').html(this.assetListView.render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
// The following works fine:
window.mylist = new VideoList();
window.mylistview = new VideoListView({model:window.mylist});
});
私はコンソールからmylist.fetch(); mylist.toJSON()
にアクセスする場合は、マイリストは罰金移入されます。 this.assetList.fetch()
はバックエンドから正確にデータを取得していますが、オブジェクトをthis.assetList
に追加しているようには見えません。
をですから、イベントを結合整理する方法について良い提案を行うなど、しかし、もしあなたは私の問題が何かを説明しました、私はそれを見逃してしまったのでしょうか? *** 気にしないでクリックしました。後続のレンダリングイベントがfetch()が完了するのを待っていないので、非同期です。ありがとうございました!私はそれを試して、それがうまくいくかどうかを正しくマークするために戻ってきます。 – akoumjian
スポットがあります。ここから、イベントバインディングを使用します。 – akoumjian
@akoumjian:問題の根は、 'fetch'がサーバから取得する前にコレクションを使用しようとしていることです。私は後世のためにそれを明確にしました。イベントシステムを通じてできるだけ多くのことをすることは、多くの問題を軽減します。 –