初始模型backbone.js

时间:2014-03-26 08:30:19

标签: javascript backbone.js model-view-controller

我想创建(请坐下)一组模型。这些模型应该包含其他集合。女巫有一个名字,颜色和一系列费用。

以下是我的3个对象:

//model : Expense
var Expense = Backbone.Model.extend({
    defaults: {
        date: '',
        cost: 0,
        comment: ''
    },
    initialize: function () {
        console.log('expense : created');
    }
});
//model : Category
var Category = Backbone.Model.extend({
    defaults: {
        name: '',
        color: '#333',
        expenses: Backbone.Collection.extend({
            model: Expense
        })
    },
    initialize: function () {
        console.log('expense : created');
    }
});
//model : Wallet
var Wallet = Backbone.Model.extend({
    defaults: {
        categories: Backbone.Collection.extend({
            model: Category
        })
    },
    initialize: function () {
        console.log('wallet : created');
    }
});

我为嵌套模型做了2天的研究,但我真的找不到办法:

  • 在我的钱包上添加类别
  • 在我的类别上添加费用
  • 修改他们

您认为backbone nested modelsbackbone relational能真正帮助我吗?他们看起来很重......

我希望我的回答不是太傻,我是一个有骨干的首发,而且进入并不容易!

此致 汤姆

1 个答案:

答案 0 :(得分:1)

如果您不想为嵌套模型使用主干插件,可以执行以下操作:

//model : Expense
var Expense = Backbone.Model.extend({
    defaults: {
        date: '',
        cost: 0,
        comment: ''
    },
    initialize: function () {
        console.log('expense : created');
    }
});

//collection : Expenses
var Expenses = Backbone.Collection.extend({
    model: Expense
});

//model : Category
var Category = Backbone.Model.extend({
  defaults: {
    name: '',
    color: '#333'
  },
  initialize: function () {
    this._ensureExpenses();
    console.log('expense : created');
  },
  parse: function(data){
    if(data.expenses){
      this._ensureExpenses();
      this.expenses.set(data.expenses, {parse: true});
    }
    return _.omit(data, 'expenses'); 
  },    
  toJSON: function(){
    return _.extend(_.clone(this.attributes), {
      expenses: this.expenses.toJSON()
    });
  },
  _ensureExpenses: function(){
    this.expenses = this.expenses || new Expenses();
  }
});

//collection : Categories
var Categories = Backbone.Collection.extend({
  model: Category
});

//model : Wallet
var Wallet = Backbone.Model.extend({
  initialize: function () { 
    this._ensureCategories();
    console.log('wallet : created');
  },
  parse: function(data){
    if(data.categories){
      this._ensureCategories();
      this.categories.set(data.categories, {parse: true});
    }
    return _.omit(data, 'categories'); 
  },
  toJSON: function(){
    return _.extend(_.clone(this.attributes), {
      categories: this.categories.toJSON()
    });
  },
  _ensureCategories: function(){
    this.categories = this.categories || new Categories();
  }
});

如果您不需要将钱包序列化为普通JS对象或JSON,则可以删除toJSON方法。

您可以在此处进行测试:http://jsbin.com/luruvifi/1/edit?js,console