检测主干模型更改以启用表单保存按钮并更新模型

detecting backbone model changes to enable save button of form and update model

本文关键字:模型 保存 表单 按钮 启用 更新 检测      更新时间:2023-09-26

我的简单表单模板是这样的

<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');
            }
        });
    }
}

还有,看看我在原帖下面的评论