1

我第一次看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>

我所看到的只是两个“欢迎来到这个世界”警报。有任何想法吗?

4

1 回答 1

3

您的源代码可能基于旧版本的 Backbone,Model.validate随着时间的推移发生了相当大的变化。

更新日志

0.9.10:模型验证现在仅在 Model#save 中默认强制执行,并且在构造或 Model#set 中不再默认强制执行,除非{validate:true}通过了该选项。

validate model.validate(attributes, options)
此方法未定义,如果您有任何可以在 JavaScript 中执行的验证逻辑,我们鼓励您使用自定义验证逻辑覆盖它。默认情况下 validate 在保存之前调用,但如果 {validate:true} 被传递,也可以在设置之前调用。[...]验证失败会触发“无效”事件

所以 :

  • 要在设置属性时验证您的模型,请使用validate:true选项
  • 绑定到invalid事件
  • 并使用Events.on而不是弃用的绑定

您的代码可能如下所示

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

还有一个 Fiddle http://jsfiddle.net/nikoshr/udm8A/(一定要打开一个控制台,我将alert调用转换为console.log

于 2013-03-19T14:02:06.153 回答