检测主干模型更改以启用表单保存按钮并更新模型
detecting backbone model changes to enable save button of form and update model
我的简单表单模板是这样的
<script type="text/template" id="template">
<form id="myForm " >
<fieldset>
<label>Name</label>
<input type="text" id="name" name="name" />
<label>Age</label>
<input type="text" id="age" name="age" />
<input type="hidden" id="id" name="id"/>
</fieldset>
<a id="save" disabled >Save Changes</a>
我的主要观点如下:
myView = Backbone.View.extend({
template: _.template( $("#template").html() ),
events: {
"click #save" : "save",
},
bindings: {
'#id': 'id',
'#name': 'name',
'#age': 'age'
},
initialize: function () {
if(this.model){
this.model.fetch();
}
this.listenTo(this.model, 'all', this.render);
},
render: function () {
this.$el.html( this.template );
this.stickit(); //used library http://nytimes.github.io/backbone.stickit/
},
save: function() {
//how to do following
//save model
//if success, reset form to new value
//if error, do not reset form and alert there is error in saving
}
}
MY view get initialize from here
RegionManager.show(new app.myView({
model : new app.myModel(
{id: 1})
}));
在这里,我的表单成功地显示了带有姓名和年龄字段的表单。它们显示在禁用保存的表单。这里表单是禁用的。现在,当用户更改任何值时,它应该立即检测并启用保存按钮,看起来应该像这个表单保存启用。在这里,只要用户追加y到mickey,保存就会被启用。现在,当用户单击save时,如果成功,则应该保存,否则应该提示错误。如果成功,应该显示更新后的表单。
我是一个新手,正在努力找出以上两个解决方案。
只要对表单进行了任何更改,stickkit就会更新将触发更改事件的模型。您可以在initialize
中设置侦听器以启用save:
this.listenTo(this.model, 'change', function() { this.$('#save').prop('disabled', false); });
在save中,您可以使用任何jQuery ajax回调函数和属性,因此您需要做如下操作:
save: function() {
if (!this.$('#save').prop('disabled')) {
this.model.save({
success: function() {
// You don't really need to do anything here. If the model was changed in the
// save process, then stickit will sync those changes to the form automatically.
},
error: function(model, xhr, options) {
alert('Formatted error message. You can use the xhr.responseText, but that may not be user friendly');
}
});
}
}
还有,看看我在原帖下面的评论
相关文章:
- 将JavaScript变量保存到Rails模型
- 一次保存多个主干模型
- 保存两个模型(属于第三个模型)和一个提交
- 主干模型:保存时保留集合
- Ember.js模型保存不向服务器发送数据
- 骨干 js 模型 保存不止一次
- 扩展主干模型保存
- 主干模型保存阻止 UI
- 骨干模型保存问题
- 主干模型保存:将字段作为“模型”子对象发送
- 测试Backbone.js模型保存使用Sinon不调用成功回调
- 使用相同的ng模型保存动态生成的输入网格
- 如何在cakeHP中为关联模型保存多个字段
- 如何使用主干模型保存发送额外的数据到服务器
- 主干模型保存
- 主干模型保存和回调问题
- 模型.保存设置url并在成功时进行回调
- 猫鼬模型保存回调的问题
- 如何将模型保存到数据库
- 主干:模型保存上的两个更改事件