通过推送更新类型数组的Backbone模型属性

时间:2012-11-25 16:36:53

标签: javascript backbone.js model

这真的是在Backbone模型中将项目添加到数组的最佳方法吗?

// TODO: is there a better syntax for this?
this.set(
    'tags',
    this.get('tags').push('newTag')
)

2 个答案:

答案 0 :(得分:5)

您可以像这样实现model.push:

var model, Model;

Model = Backbone.Model.extend({
  defaults: { tags: [] },
  push: function(arg, val) {
    var arr = _.clone(this.get(arg));
    arr.push(val);
    this.set(arg, arr);
  }
});
model = new Model;
model.on("change:tags", function(model, newTags) {
  console.log(newTags)
});
model.push("tags", "New tag1")
model.push("tags", "New tag2")

但也许您应该在Collection中存储标签,聆听其事件并更新模型tags属性。

var model, Model, Tags, Tag;

// Override id attribute for Tag model
Tag = Backbone.Model.extend({
  idAttribute: "name"
});

Tags = Backbone.Collection.extend({model: Tag});

Model = Backbone.Model.extend({
  initialize: function() {
    this.tags = new Tags;
    this.tags.on("add remove reset", this.updateTags, this);
  },
  updateTags: function() {
    this.set("tags", this.tags.pluck("name"))
  }
});

model = new Model;
model.on("change:tags", function(model, newTags) {
  console.log(newTags)
});

// Reset tags
model.tags.reset([{name: "New tag1"}, {name: "New tag2"}]);

// Add tags
model.tags.add({name: "New tag3"});

// Remove tag
model.tags.remove(model.tags.get("New tag3"));

答案 1 :(得分:0)

如果您的模型的属性是这样的数组

TestModel = Backbone.Model.extend({
  defaults:{
    return {
       things:[]
    }
  }
});

将项目添加到模型TestModel上的内容

var test = new TestModel;
test.set({things:item});