backbone.js Model Creating models


Example

Backbone models describe how data is stored using JavaScript objects. Each model is a hash of fields called attributes and the behaviour of the model including validation is described by options.

A model of Todo item in a TodoApp would be

var ToDo = Backbone.Model.extend({
  defaults: {
    assignee: '',
    task: ''
  },

  validate: function(attrs) {
    var errors = {},
        hasError = false;

    if(!attrs.assignee) {
      errors.assignee = 'assignee must be set';
      hasError = true;
    }

    if(!attrs.task) {
      errors.task = 'task must be set';
      hasError = true;
    }

    if(hasError) {
      return errors;
    }
  }
});