问题
MY simple form template is like this
<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>
My bakbone view is as follows:
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})
}));
Here my form successfully display form with name and and age feild. They appear as shown in form with save disabled. Here form is disabled. Now, when user changes any value, it should detect immediately and save button should be enabled and should look like this form save enabled. Here save is enabled as soon as user append y to mickey. Now, when user click save, it should be save if successful else it should alert error. if successful, it should show updated form.
I am new to backbone and trying to figure out above two solutions.
回答1:
As soon as any change has been made to the form, stickit will update the model which will trigger change events. You can setup a listener in initialize
to enable save:
this.listenTo(this.model, 'change', function() { this.$('#save').prop('disabled', false); });
In save, you can use any of the jQuery ajax callbacks and properties, so you'll want to do something like the following:
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');
}
});
}
}
Also, check out my comment under the original posting.
来源:https://stackoverflow.com/questions/16099102/detecting-backbone-model-changes-to-enable-save-button-of-form-and-update-model