のビューが必要なのか、単一の を処理するビューが必要なCollection
のかよくわかりません。Models
Model
単体モデルのビューであれば、
そうすれば、1 つのビューに固執することができます。編集機能を有効または無効にするアクションをリッスンするイベントをいくつか用意するだけです。(dom 要素に contenteditable="true" を設定することでもこれを行うことができます)
backbone.marionetteや chaplinjsなどのツールを使用することを強くお勧めします。彼らはあなたの時間を大幅に節約します。
以下は Backbone.Marionette の例です。
例のテンプレート
<script type="text/template" id="contact-view-template">
<span data-bind="firstName"></span>
<span data-bind="lastName"></span>
<span data-bind="email"></span>
<a href="#" data-action="edit">
<a href="#" data-action="save" style="display:none">
</script>
ビューコード:
ContactView = Marionette.ItemView.extend({
template:"#contact-view-template",
events:{
"click [data-action=edit]":"edit",
"click [data-action=save]":"save"
},
edit:function(){
this.$("[data-action=edit]").hide();
this.$("[data-action=save]").show();
this.$("[data-bind]").attr("contenteditable",true);
},
save:function(){
var value = {};
_.each(this.$("[data-bind]",function(el){
value[el.dataset['bind']]= $(el).val() || $(el).text();
}));
this.model.set(value);
// add your validation here
this.model.save();
}
});
複数の編集ビューが必要な場合は、次のようにします。
ContactListEditView = Marionette.CompositeView.extend({
itemView:ContactView.extend({
tagName:"li"
}),
itemViewContainer:"ul",
template:_.template("<h1>ContactList</h1><p>feel free to edit</p><ul></ul>")
});
1 つの編集ビューと複数の編集不可ビューが必要な場合
(重大なエラーが発生していないことを願っています):
ContactEditView = Marionette.ItemView.extend({
template:"#contact-edit-view", // your template & bindings
events:{
"click [data-action=save]":"save"
},
save:function(){
var value = {};
_.each(this.$("[data-bind]",function(el){
value[el.dataset['bind']]= $(el).val() || $(el).text();
}));
this.model.set(value);
this.model.save();
}
});
ContactListView = Marionette.CompositeView.extend({
itemView:Marionette.ItemView.extend({
template:"#contact-view-template",
events:{
"click [data-action=edit]":"edit"
},
edit:function(){
this.trigger("edit",this);
}
}),
regions:{
"edit":"[data-region=edit]"
},
initialize:function(){
this.on("itemview:edit",function(view){
this.edit.show(new ContactEditView({model:view.model}));
}.bind(this));
}
});