2

I see a difference using create() and push() on collections using Backfire and wonder if this is a misunderstanding on my part, or a bug.

I have an Animal model and Animals collection as below. Normally, the collection is created with an options object containing a zoo_id which is then used to populate the zoo_id in new models. It's a fixed value for this example.

var Animal = Backbone.Model.extend({
      initialize: function(attributes, options) {
        console.log("model initializing", attributes, options)
      }
    }),
    Animals = Backbone.Firebase.Collection.extend({
      firebase: myFirebaseUrl + "/animal",
      initialize: function(models, options) {
        this.model = function(attrs, opts) {
          return new Animal(_.extend(attrs, {zoo_id: 4}))
        };
        this.on("add", function(model, collection, options) {
          console.log("adding", model, collection, options, model.attributes)
        })
      }
    })
var a= new Animals()

If there's data in Firebase, all of the retrieved animal models in a[] have zoo_id = 4, as expected.

When I push a new model

a.push({name: "racoon"})

all of the attribute objects logged to the console have zoo_id = 4. However, the returned object does not have a zoo_id, nor is zoo_id present for the new entry in the Forge.

When I create a new model

a.create({name: "ape"})

all of the attribute objects logged to the console have zoo_id = 4, the returned object has zoo_id = 4, and the new entry has zoo_id = 4 is in the Forge.

If I remove the Firebase extensions and just use a regular Backbone model and collection in the same manner, push returns an object with a zoo_id, and create fails as there's no url set up (as expected).

thanks in advance for clarification!

Musa
  • 96,336
  • 17
  • 118
  • 137

1 Answers1

1

Push is not part of the functionality overridden by the Backfire API. It pretty much sticks to the same contract as Backbone.Collection. Thus, push simply appends a record to the end of the array without syncing it to any back end.

You could probably create the desired behavior by calling sync after push, as would normally be done with a Backbone collection. I'm not sure how the id would work here, you might need to add one onto the object before it can be synchronized.

However, it's probably simplest to use create/add instead, which are part of BackFire's API and handle server synchronization.

Kato
  • 40,352
  • 6
  • 119
  • 149
  • Kato - we discussed this via email, and I should have closed this when I added opened the github issue at your suggestion: https://github.com/firebase/backfire/issues/75 Push() just calls add with an index. add() and create() don't work the same way. – Mike Franklin Jul 27 '14 at 14:25