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

Javascript 检测主干模型更改以启用表单的保存按钮并更新模型,javascript,backbone-views,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="

我的简单表单模板如下

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

从这里开始初始化我的视图

RegionManager.show(new app.myView({
 model : new app.myModel(
 {id: 1})
}));
在这里,我的表单成功地显示了带有姓名和年龄字段的表单。它们的显示方式如中所示 . 这里的表单被禁用。现在,当用户更改任何值时,它应该立即检测并启用save按钮,看起来应该是这样的。在这里,只要用户将y附加到mickey,就会启用“保存”。现在,当用户单击“保存”时,如果成功,则应将其保存,否则应警告错误。如果成功,则应显示更新的表单


我对主干网还不熟悉,正在尝试找出以上两种解决方案。

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

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

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

为什么在模型上触发任何事件后重新渲染?如果您使用stickit绑定,那么我认为不需要这样做,除非模板中有更多内容需要刷新(但也可以使用stickit连接)。我已经能够保存模型。我只是想检测表单值的任何更改。如果表单值为原始值,则应禁用保存。如果该值已更改,则应启用“保存”。代码没有发出声音。安维,谢谢
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');
            }
        });
    }
}