检测骨干模型更改,以启用表单保存按钮和更新模型

时间:2013-04-19 07:08:38

标签: javascript backbone-views

我的简单表单模板就像这样

<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>

我的bakbone视图如下:

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
}

}

我的观点从这里开始初始化

RegionManager.show(new app.myView({
 model : new app.myModel(
 {id: 1})
}));

这里我的表单成功显示了名称和年龄段的表单。它们如图所示 form with save disabled。此表单已禁用。现在,当用户更改任何值时,它应该立即检测并且应该启用保存按钮,并且应该看起来像form save enabled。只要用户将y附加到mickey,就会启用保存。现在,当用户单击“保存”时,如果成功则应该保存,否则应该提示错误。如果成功,它应该显示更新的表格。

我是骨干新手并试图找出上述两种解决方案。

1 个答案:

答案 0 :(得分:1)

只要对表单进行了任何更改,stickit就会更新将触发更改事件的模型。您可以在initialize中设置一个侦听器以启用保存:

this.listenTo(this.model, 'change', function() { this.$('#save').prop('disabled', false); });

在保存中,您可以使用任何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');
            }
        });
    }
}

另外,请查看原始帖子下的评论。

相关问题