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

Sim*_*lGy 1 javascript model backbone.js

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

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

And*_*min 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")
Run Code Online (Sandbox Code Playgroud)

但也许您应该在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"));
Run Code Online (Sandbox Code Playgroud)