0
votes

I was wondering if there's a way to specify model attributes that must be initialized upon instantiation.

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

});

and whenever I instantiate the model, I wish to constrain that these few attributes have to be initialized, or at least constrain enough not to be able to set a new attribute:

var book = new Book({
  title: "something",
  pages: "350"
});
2
To clarify, are you trying to protect these attributes from change?Mild Fuzz
no, I'd like to model a relational database in a way. If we create database with 3 columns and try to insert data into a non-existing column, we get an error. I'm trying to model similar behavior, so in this example, you'd be only able to assign values to these 3 attributes. if that's possible in backbone.Mefhisto1
Have you tried my solution ?Rida BENHAMMANE
Yes, I just thought there was an out-of-the-box solution backbone provided, but yes, this will workMefhisto1

2 Answers

2
votes

Try this :

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

If you want to constrain to those attribute you can do it using validate method :

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

try


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