Creating a new firebase listener on fly

61 views
Skip to first unread message

Rituraj

unread,
Jul 22, 2016, 1:23:08 AM7/22/16
to Firebase + EmberJS
Hi
I am trying to add firebase realtime database in my ember app.
I am creating a firebase listener dynamically., but it is not working.
What am i doing wrong ?

Ember app:

index.html


   
<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
   
<script>
     
// Initialize Firebase
     
var config = {
        apiKey
: "myapikey",
        authDomain
: "test.firebaseapp.com",
        databaseURL
: "https://test.firebaseio.com",
        storageBucket
: "test.appspot.com",
     
};
      firebase
.initializeApp(config);
   
</script>


ember.js controller


import Ember from 'ember';


export default Ember.Controller.extend({


   dataBasePath
: null,


   updateNewValue
: function() {
   
// do some funny
   
},


  listner
: firebase.database().ref(dataBasePath).on('value', function(snapshot) {
   
this.updateNewValue();
 
}),

Rituraj

unread,
Jul 22, 2016, 1:30:53 AM7/22/16
to Firebase + EmberJS
dataBasePath is set from route.

 setupController: function(controller, model) {
    controller
.set('model', model);
    controller
.set('dataBasePath', "/subject");
 
},

Tim Stirrat

unread,
Jul 22, 2016, 2:38:18 PM7/22/16
to Rituraj, Firebase + EmberJS
Hi Rituraj,

There are a couple of things to note here with your code, specifically this snippet:

listner: firebase.database().ref(dataBasePath).on('value', function(snapshot) {
  this.updateNewValue();
}),
  • dataBasePath is not available to you when the controller is initialized, it is set later. You need to wait for the property to be set with Ember.computed or Ember.observer.
  • You should access the value of dataBasePath with this.get('dataBasePath')
  • this.updateValue() will throw an error, because the value of `this` is undefined inside the callback, you can use Ember.run.bind() to fix that.

Here is something that applies the notes from above:

export default Ember.Controller.extend({
  value: null,
  
  listener: Ember.observer('dataBasePath', function() {
    var ref = firebase.database().ref();
    ref.child(this.get('dataBasePath'))
      .on('value', Ember.run.bind(this, this.updateNewValue));
  }),

  updateNewValue: function(snapshot) {
    this.set('value', snapshot.val());
  }
});

Hope that helps,

Tim

--
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.

Rituraj

unread,
Jul 25, 2016, 1:24:43 AM7/25/16
to Firebase + EmberJS, ritur...@gmail.com
Thanks Tim.
Reply all
Reply to author
Forward
0 new messages