SimplGy
SimplGy

Reputation: 20437

Update a Backbone model property of type array by pushing

Is this really the best way to add an item to an array in a Backbone Model?

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

Upvotes: 1

Views: 3526

Answers (2)

Andrey Kuzmin
Andrey Kuzmin

Reputation: 4479

You can implement model.push like this:

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")

But maybe you should store tags in Collection, listen to its events and update models tags attribute.

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"));

Upvotes: 5

jonezy
jonezy

Reputation: 1923

If you have a model with an attribute that is an array like this

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

to add an item to things on model TestModel

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

Upvotes: 0

Related Questions