我第一次看到backbone.js。我目前正在查看模型验证,但是我直接从教学文本中获取的这个测试脚本没有按预期触发错误事件。
Person = Backbone.Model.extend({
// If you return a string from the validate function,
// Backbone will throw an error
validate: function(attributes) {
if (attributes.age < 0 && attributes.name != "Dr Manhatten") {
return "You can't be negative years old";
}
},
initialize: function() {
alert("Welcome to this world");
this.bind("error", function(model, error) {
// We have received an error, log it, alert it or forget it :)
alert(error);
});
}
});
var person = new Person;
person.set({ name: "Mary Poppins", age: -1 });
// Will trigger an alert outputting the error
var person = new Person;
person.set({ name: "Dr Manhatten", age: -1 });
// God have mercy on our souls
我的测试页面简单如下:
<html>
<body>
<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="Scripts/underscore-min.js"></script>
<script type="text/javascript" src="Scripts/backbone-min.js"></script>
<script type="text/javascript" src="Scripts/test4.js"></script>
</body>
</html>
我所看到的只是两个“欢迎来到这个世界”的警报。有什么想法吗?
答案 0 :(得分:3)
您的源代码可能基于较旧版本的Backbone,Model.validate随着时间的推移发生了很大变化。
0.9.10:模型验证现在仅在Model#save中默认强制执行,默认情况下不再强制执行 在构造或模型#set中,除非传递
{validate:true}
选项。
和
验证 model.validate(属性,选项)
此方法未定义,建议您使用自定义覆盖它 验证逻辑,如果你有任何可以在JavaScript中执行的。 默认情况下,在保存之前调用validate,但也可以调用 在设置之前,如果传递{validate:true} 。 [...] 失败的验证会触发“无效”事件。
所以:
validate:true
选项invalid
事件您的代码可能如下所示
Person = Backbone.Model.extend({
// If you return a string from the validate function,
// Backbone will throw an error
validate: function(attributes) {
if (attributes.age < 0 && attributes.name != "Dr Manhatten") {
return "You can't be negative years old";
}
},
initialize: function() {
console.log("Welcome to this world");
this.on("invalid", function(model, error) {
// We have received an error, log it, alert it or forget it :)
console.log(error);
});
}
});
var person = new Person;
person.set({ name: "Mary Poppins", age: -1 }, {validate:true});
// Will trigger an alert outputting the error
var person = new Person;
person.set({ name: "Dr Manhatten", age: -1 }, {validate:true});
小提琴http://jsfiddle.net/nikoshr/udm8A/(请务必打开控制台,我将alert
来电转换为console.log
)