私はバックボーンとアンダースコアに比較的慣れていないので、実際には問題ではない質問の 1 つがあります。好奇心から私を悩ませているだけです。
コレクション内でモデルを追加および削除し、それらをブラウザーでレンダリングできる非常に単純なアプリを作成しました。また、コレクションする機能もありconsole.log
ます (自分のコレクションを見ることができます)。
奇妙なことに、ID が生成さ1,3,5...
れます。私のコードに固有の理由がありますか、それとも BB/US と関係がありますか?
これが機能するフィドルです:http://jsfiddle.net/ptagp/
そしてコード:
App = (function(){
var AppModel = Backbone.Model.extend({
defaults: {
id: null,
item: null
}
});
var AppCollection = Backbone.Collection.extend({
model: AppModel
});
var AppView = Backbone.View.extend({
el: $('#app'),
newfield: $('#new-item'),
initialize: function(){
this.el = $(this.el);
},
events: {
'click #add-new': 'addItem',
'click .remove-item': 'removeItem',
'click #print-collection': 'printCollection'
},
template: $('#item-template').html(),
render: function(model){
var templ = _.template(this.template);
this.el.append(templ({
id: model.get('id'),
item: model.get('item')
}));
},
addItem: function(){
var NewModel = new AppModel({
id: _.uniqueId(),
item: this.newfield.val()
});
this.collection.add(NewModel);
this.render(NewModel);
},
removeItem: function(e){
var id = this.$(e.currentTarget).parent('div').data('id');
var model = this.collection.get(id);
this.collection.remove(model);
$(e.target).parent('div').remove();
},
printCollection: function(){
this.collection.each(function(model){
console.log(model.get('id')+': '+model.get('item'));
});
}
});
return {
start: function(){
new AppView({
collection: new AppCollection()
});
}
};
});
$(function(){ new App().start(); });