1

这真的是向主干模型中的数组添加项目的最佳方式吗?

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

2 回答 2

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"));
于 2012-11-25T17:14:51.237 回答
0

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

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

向模型 TestModel 上的事物添加项目

var test = new TestModel;
test.set({things:item});
于 2012-11-25T16:46:59.000 回答