我一直在努力学习 Backbone。
我设置了模型集合,每个模型都有自己的视图,每次模型与服务器同步时都应该渲染。服务器发回模型的 ID。它似乎在模型 ID 设置之前渲染。如果您查看 console.log() 输出,我让它在渲染之前打印模型的 id。我还让它在每个事件发生时打印它。我得到:
undefined (model id)
add
change:id
change (not sure what changes here?)
sync
另外,我让它在 2 秒 pause 后更改模型的 name 属性model.save('name', 'New Name')
。这会导致另一个同步事件,但视图不会更新。
这是工作代码:http: //jsfiddle.net/flackend/brB7y/1/
或者在这里查看:
var game_library;
(function($) {
_.templateSettings = {
interpolate: /\{(.+?)\}/g
};
var GameModel = Backbone.Model.extend({
url: '/gh/gist/response.json/2895708/',
name: undefined,
initialize: function() {
// Create a view for this model
this.view = new GameView({model: this});
// Sync model with server
this.save();
// Bind events
this.on('sync', this.view.render());
this.on('all', this.console);
},
console: function(event, model, changes) {
console.log('['+ ++this.i +']-------------(event[:attr], model, changes)----------------');
console.log(event);
console.log(model);
console.log(changes);
},
i: 0
});
var GameCollection = Backbone.Collection.extend({
model: GameModel
});
var GameView = Backbone.View.extend({
el: $('#holder'),
template: $('#game-template').html(),
render: function() {
var template = _.template(this.template);
console.log(this.model.id);
this.$el.html(template(this.model.toJSON()));
}
});
// Instantiate new game collection
game_library = new GameCollection;
// Add a game
// Note: can only pass in 1 ID from gist, so only add 1 game.
var games = [
new GameModel({name: 'Skyrim'})
];
// Note: `game_library.add(new GameModel({name: 'Skyrim'}));` does
// not work for some reason having to do with instances...
game_library.add(games);
// 2 sec later...
window.setTimeout(function() {
game_library.get(1).save('name', 'The Elder Scrolls V: Skyrim');
}, 2000);
})( jQuery );
感谢您的帮助!</p>