Backbone.js模型,指定属性

时间:2014-02-19 10:07:51

标签: javascript backbone.js model

我想知道是否有办法指定必须在实例化时初始化的模型属性。

Book = Backbone.Model.extent({
 title: "title",
 author: "author",
 year: "year"

});

每当我实例化模型时,我希望限制这几个属性必须初始化,或者至少足以限制不能设置新属性:

var book = new Book({
  title: "something",
  pages: "350"
});

2 个答案:

答案 0 :(得分:2)

试试这个:

Book = Backbone.Model.extent({
    defaults: {
     title: "title",
     author: "author",
     year: "year"
    }
});

如果要约束这些属性,可以使用validate方法:

Book = Backbone.Model.extent({
    defaults: {
     title: "title",
     author: "author",
     year: "year"
    },

    validate: function(attrs, options) {
        var isValid = true;
        _.each(_.keys(attrs), function(key) {
            if (!this.defaults[key]) {
                isValid = false;
            }
        }, this);
        return isValid;
    }
});

答案 1 :(得分:0)

尝试


Book = Backbone.Model.extend({ 
defaults: {
     title: "title",
     author: "author",
     year: "year"
    }
});