骨干模型保持不变
我的应用程序使用 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!!');
});
My app uses Backbone. It has a model that users can change. This model must be validated before being changed. If it has changed, a function is called. When users click on save, the model is saved if and only if it has changed.
My problem is that when the change event is fired the model has no longer changed, therefore it will not be saved.
Here is the code: 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!!');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论