Writing to an array

9 views
Skip to first unread message

bra...@southbendcodeschool.com

unread,
May 22, 2016, 4:44:51 PM5/22/16
to Firebase + EmberJS
I want to keep an array at the root of my database.

/active_things
   - thing_id: true
   - thing_id2: true


elsewhere, there is already a relationship between thing and owner.  I just want to add an array entry to active_things when I create a Thing.  I'm not clear how to model this for emberfire.  Any tips, or is there a way I can just straight-up write a key/value pair to active_things?

bra...@southbendcodeschool.com

unread,
May 22, 2016, 4:58:48 PM5/22/16
to Firebase + EmberJS
is it possible to get an emberfire reference to the root of the database?

Tim Stirrat

unread,
May 22, 2016, 7:16:57 PM5/22/16
to bra...@southbendcodeschool.com, Firebase + EmberJS
Hi Brandon,

Yes, you can get a ref to the root by using the firebase service:

firebase: Ember.inject.service(),

someMethod() {
  const ref = this.get('firebase');
}

As for the initial question, if you were happy to move the "array" location down a few levels in the firebase DB, you could use a singleton EmberFire model:

// app/models/thing-collection.js
export default Ember.Model.extend({
  activeThings: DS.hasMany('thing', {async: true})
});

Then you would always fetch the singleton thingCollection with id '1' and this can be your source of truth:

model() {
  return this.store.findRecord('thingCollection', '1');
},

actions: {
  someAction() {
    this.store.createRecord('thing', {x: 'y'})
      .save()
      .then((r) => {
        const model = this.get('model');
        model.get('activeThings').pushObject(r);
        return model.save();
      });
  }
}

If you really don't want to do that, you could use a raw ref and listen to the 'child_added', 'child_removed' events and pump this into an Ember array manually:

const activeThings = Ember.A();

ref.on('child_added', (snap) => {
  const id = snap.key();
  this.store.findRecord('thing', id).then(t => activeThings.pushObject(t));
});

ref.on('child_removed', (snap) => {
  const id = snap.key();
  // if peekRecord finds it, no need to findRecord again
  const thing = this.store.peekRecord('thing', id);
  if (thing) {
    activeThings.removeObject(t);
  }
});

Hope that gives you some ideas to work with,

🔥

Tim


On Mon, May 23, 2016 at 6:58 AM <bra...@southbendcodeschool.com> wrote:
is it possible to get an emberfire reference to the root of the database?

--
You received this message because you are subscribed to the Google Groups "Firebase + EmberJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-embe...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages