Noob Q: How to perform Queries using Backfire (Backbone)?

56 views
Skip to first unread message

PeteM

unread,
Oct 24, 2014, 12:45:43 PM10/24/14
to fireba...@googlegroups.com
I'm learning Backbone and trying to integrate Firebase via their Backfire extension. I'm following the 'Queries, Part 1' article on firebase.com which seem pretty clear on their own but.. I'm not too sure how to translate it into a Backbone/Backfire environment.

Let's say I've instantiated a collection of Users:

var UsersCollection = Backbone.Firebase.Collection.extend({
    model: UserModel,
    firebase: new Firebase("https://xxxxxx.firebaseio.com/users")
});
var Users = new UsersCollection();

...and I have a template rendering the full list, works fine: 

var context  = { allUsers: Users.toJSON() };
this.$el.html( this.template( context ) );

Now, let's say, in my View I want to filter the collection down to a specific id, or email address, or dates based on some logic, and re-render the template with the result -- a shorter list, or a single record.

To get a single record, I tried doing things like:   Users.get(id).toJSON() but the template no longer renders anything (although an object is returned when I log it..)

If I wanted a more complex query on this data, let's say between specific dates, or even the last 10 records, would I need to define and re-instantiate a whole new Collection at this point?? Sorry, coming from Django, just trying to figure out the right way to do it..

Thanks!


David East

unread,
Oct 24, 2014, 7:22:08 PM10/24/14
to fireba...@googlegroups.com
Hey Pete,

You have the right idea. To add in a query you would need to call your query on reference and create a new collection.

var LimitedUsersCollection = Backbone.Firebase.Collection.extend({
    model: UserModel,
    firebase: new Firebase("https://xxxxxx.firebaseio.com/users").limit(10)
});
var limitedCollection = new LimitedUsersCollection();

BackFire doesn't have the greatest support of querying right now, but I'm working on fixing that. If you're interested in doing some user testing on a beta version of BackFire please let me know!
Message has been deleted
Message has been deleted
Message has been deleted

PeteM

unread,
Oct 29, 2014, 1:50:05 AM10/29/14
to fireba...@googlegroups.com
Made progress. Per David @ Firebase, the proper way to set up a Firebase-backed Collection is:

   var MyCollection = Backbone.Firebase.Collection.extend({
      model: MyModel,
      firebase: "https://xxxxxx.firebaseio.com"    <--- !!!
   });


Once I got it working, I'm now able to use Backbone's native Collection methods on it, e.g. get(), findWhere(), sort(), etc. I can also update select model properties using model.set() and so on, and the data are automatically synced to Firebase.  Sweet!
Reply all
Reply to author
Forward
0 new messages