我的应用程序使用 Backbone。它有一个用户可以更改的模型。此模型在更改之前必须经过验证。如果它已更改,则调用一个函数。当用户单击保存时,当且仅当模型发生更改时,模型才会被保存。
我的问题是,当更改事件被触发时,模型不再更改,因此它不会被保存。
这是代码:http: //jsfiddle.net/keepyourweb/jQL8V/
var model = Backbone.Model.extend({
initialize: function() {
},
default: {
'first_name': 'none',
'last_name': 'none'
},
validate: function(attr) {
if (_.isEmpty(attr['first_name'])) return 'Error name required';
}
});
var test = new model,
showError = function(model, error) {
alert(error);
},
changed = function() {
alert('changed!');
};
test.bind('change', changed);
test.set({'first_name': 'test_name', 'last_name': 'test_surname'}, {error: showError});
$('#save').bind('click', function() {
if (test.hasChanged()) alert('Saved!!');
});