Archive for the ‘Backbone.js’ category

Backbone collection sorting.

May 14th, 2013

Recently I had a need to sort a list of records in a list by the Date it was created and I wanted to do so using backbone, well it turns out there is a very simple and slick way to get this done, I have included the code snippets below:

The collection:

], function (backbone, model) {
    return backbone.Collection.extend({
        url: '/your_url/',
        model: model,
        sort_key: 'id', // default sort key
        comparator: function (item) {
            return -item.get(this.sort_key);
        sortByField: function (fieldName) {
            this.sort_key = fieldName;

As you can see you just use the comparator: function built into the backbone collections and in my example I am passing a negative so that it will sort descending, the default is ascending so just leave the minus sign off if you want it to work that way. I included the sortByField function here as a convenient way to call it in the code off the collection, it uses the sort_key field in the comparator to organize your collection. Below I have the usage, as you can see, its just a simple call to the string name of the field you want to sort by.

The usage:

new collection().fetch({
                data: { data: "whatever" },
                success: function (r) {
                error: function (c, r) {
                    alert("Error retrieving the data.");

Be very careful when you set the id of a Backbone model

May 10th, 2013

I have been scratching my head all morning today trying to figure out why a collection I had on my backbone model was getting reset anytime I passed it to my views.  I tried everything, passing the collection to my view in functions, instantiating it in the initialize(), and a few other things that I can’t even remember right now, lol.  Anyways, I noticed down where we were adding items to the collection there was a line that looked like this:

that.model.set(“id”, evt.val, { silent: true });

Notice the lowercase “id” there.  What that is telling backbone is to actually set the id of the model instead of just setting the id to something we had planned to reference down the road, which would be fine in most situations, although I think backbone will do a PUT in those situations because it thinks the model has been saved before.  Anyways, when this was set in my app, it was clearing the collection whenever I passed it around, which was not cool.  All I had to do was change that to an uppercase “Id” and update any reference I had to it and all is well again, my collection stays intact.  I hope this helps someone.

How to correctly use the parse function in backbone.js

January 5th, 2013

Ok, I have been looking for this example for a long time myself, so I thought I would post it to my blog for anybody strugging with this themselves. When you use fetch() to get a collection it does a great job of setting the properties of your model, the one thing it does not do is set nested collections, so I have an example below of using backbone’s parse() function and how to take your response that has arrays on it and turn those into new collections and set it back to your main model.

If you would rather use a library and have all your models structured nicely to have backbone handle the work for you, and you have a project that has a lot of models and collections, I would recommend looking into the Backbone-Relational library, it looks very nice. I kinda like to do my own thing and not get the overhead that comes with a third-party, plus this code is very small, vs. the amount of extra you would get with the third party, enjoy.

parse: function (response) {
            if (response != null) {
                response.YourCollection = new yourCollection(response.YourCollection);
                return response;

How to dynamically set the template in a Marionette ItemView

December 28th, 2012

Don’t judge me on this, I am just trying to offer some help, this took me a lot longer to figure out that it should have, but I am glad I figured it out and I thought I would throw this out there for anybody else struggling with it too. I beat my head into the wall trying to set the template for an itemview and it turns out it was stupid simple, as outlined in the code below:

var v = new this.options.itemsView({
    collection: l,
    itemView: yourItemView.extend({ template: "<div>yourTemplate</div>" })
//show it in your region;

As you can see, all you have to do is use the extend method of the itemView and set the template inside of that and voila. This may not be the recommended way of getting this done but it works for me and its nice and simple and allows for some very clean code. I hope this helps someone, enjoy!!

Creating a grouped tablerow using Twitter Bootstrap and Backbone Marionette

November 9th, 2012

I have been working on a project where I need data grouped or summarized by date, and I wanted to make use of Backbone and Marionette with its CompositeViews and ItemViews so I whipped up an example, check it out below

It makes use of a Marionette CompositeView to create a table and then takes that and an ItemView to create rows that are wrapped with the Twitter Bootstrap accordion control to do the collapsing of the rows, how sweet is that??

Validate Subcollections in Backbone models

October 26th, 2012

Backbone.js is an awesome library for Javascript development, and at some point in your application, probably close to the finishing point, you will want to validate your models and Backbone has provided a great function through that, find out more about that here: As I was adding validation to my models I had the need to validate my subcollections that were in my models and I just didn’t see a good way to do that besides sending up my subcollections via the posts or the save() method in backbone, which I don’t want to be doing until my main model is ready to be sent up.

I know its wrong or bad coding to be adding unvalidated models to your collections but in my situation it was necessary so I came up with a little method of validating those models, check out the snippet below:

validate: function (attrs) {
           if (attrs.Products.length == 0) {
                return "Please choose at least one product";
            } else {
                var error;
                var that = this;
                attrs.Products.each(function (prod) {
                    error = prod.validate(prod.attributes);
                if (error)
                    return error;

As you can see in the validate function of the main model it simply iterates over each ‘Product’ in the Products collection and calls validate on those products and if an error is thrown down in the product model it will bubble up to my main model and thus show the user the error. Its a simple solution that I kind of expected backbone to be able to handle for me but everybody out there just says to validate your model before it goes into the collection but there are situations where that just isn’t possible. I hope this helps someone out, have a great day!!

Make use of the “tagName” in Backbone!!

June 19th, 2012

If you are writing javascript apps and haven’t heard of Backbone, you need to start reading up, BackboneJS. It makes heavy use of underscore.js UnderscoreJS which provides a decent templating structure to lay our your html pages.

What I am trying to stress in this blog post is to make use of the tagName in the backbone view, you can read more about it here: Backbone View. This allows you to have very simple templates and let backbone do all the rendering of the html for you.

Building CouchApps (My latest adventure)

June 7th, 2012

I have been working with CouchDB for quite some time as you may have seen in my past blog posts and after a lot of research I came across the idea of a CouchApp as described here: CouchApps The idea is simple, communicate with your database straight instead of using an application server like Rails or MVC, let the database be your storage and application server. So far so good, what I especially love about how they function is the deployment aspect of it, you can deploy your site as easy as opening up your command line and typing in “couchapp push”, it really is that easy. If you couple this with Backbone.js like with this connector: Backbone-Couch Connector you have a very clean and efficient webapp. I will make more posts about this in weeks to come as I am very excited about the things I am learning about it.