ノートが要求されたときにノートを読み込みにしてみませんか?ここに例があります:
var State = Backbone.Model.extend({
defaults: {
ready: false,
error: null
}
});
var Note = Backbone.Model.extend({
initialize: function() {
this.state = new State();
}
});
var Notes = Backbone.Collection.extend({
model: Note,
initialize: function() {
this.state = new State();
}
});
var NoteCache = Backbone.Model.extend({
initialize: function() {
this._loading = false;
this._loaded = false;
this._list = new Notes();
},
_createDeferred: function (id) {
var note = new Note({ id: id });
this._list.add(note);
this._load();
return note;
},
getNote: function (id) {
return this._list.get(id) || this._createDeferred(id);
},
getNotes: function() {
if (!this._loaded)
this._load();
return this._list;
},
_load: function() {
var that = this;
if (!this._loading) {
this._list.state.set({ ready: false, error: null });
this._loading = true;
$.ajax({
url: '/api/notes',
dataType: 'json',
cache: false,
type: 'GET',
success: function (response, textStatus, jqXHR) {
_.each(response.notes, function (note) {
var n = that._list.get(note.id);
if (n) {
n.set(note);
} else {
that._list.add(note, { silent: true });
n = that._list.get(note.id);
}
n.state.set({ ready: true, error: null });
});
that._list.state.set({ ready: true, error: null });
that._list.trigger('reset', that._list);
that._loaded = true;
},
error: function (jqXHR, textStatus, errorThrown) {
that._list.state.set({ error: 'Error retrieving notes.' });
that._list.each(function (note) {
note.state.set({ error: 'Error retrieving note.' });
});
},
complete: function (jqXHR, textStatus) {
that._loading = false;
}
});
}
}
});
この例では、遅延ロードを管理するNoteCacheオブジェクトを定義しています。また、「状態」プロパティを「メモ」モデルと「メモ」コレクションに追加します。
あなたはおそらく(おそらくあなたのルート内の)どこかNoteCacheを初期化したいと思うし、あなたがノートやメモをいつでも、ちょうどこの操作を行います。
var note = noteCache.getNote(5);
var notes = noteCache.getNotes();
は今、あなたのビュー内、あなたが聴きたいですよケースの状態変化のノート/ノートがまだロードされていないために:
var NoteView = Backbone.View.extend({
initialize: function(){
this.note.state.bind('change', this.render, this);
},
render: function(){
if (this.note.state.get('error') {
// todo: show error message
return this;
}
if (!this.note.state.get('ready') {
// todo: show loader animation
return this;
}
// todo: render view
return this;
}
});
私はこれをテストしていないので、いくつかのバグがあるかもしれませんが、私はあなたのアイデアを得る願っています。
BACKBONE.JSで遅延ロード機能を構築する方法は非常に良い例をありがとうしかし、どのような場合、私はノートのような10他のリソースを持っています。私はバックボーンの低レベル部分を乱しているように感じる.js。 backbone.jsがこの機能をサポートしていない場合は、正しいパターンがすべての可能なレコードを取得するだけかもしれません。あなたが思うこと ? また、このスレッドには素晴らしいプラグインがあります。 http://stackoverflow.com/questions/7664571/handling-a-belongs-to-relation-with-backbone-js – Lewy
モデルがたくさんある場合は、すべての共通ロジックを含む基本キャッシュオブジェクトを作成できます。また、異なるキャッシュ(BaseCache、NoteCache、UserCacheなど)を継承することもできます。 –