Tag Archives: backbone

Running Jasmine Tests With PhantomJS

Jasmine + PhantomJSI finally got to mess around with PhantomJS and Jasmine, and couldn’t find a resource that gives clear, concise, accurate information, without language specific or build tool specific coupling, so I decided to write it myself.
Fortunately, it is way simpler than I thought.

PhantomJS

PhantomJS is a standalone, cross platform command line application which does not require any specific server environment or programming language support.

Continue reading

3 Tips For Writing Better Backbone Views

Backbone
One of the good things about Backbone.js is it doesn’t tell us how to do things. It leaves it for us to decide what are the best practices for writing views (or any components).
This is also one of the worst things about Backbone. it makes it almost too easy to take the wrong path, and write views that will be hard to maintain.
The principle we should follow when writing a view is to keep it encapsulated, and keep it as “dumb” as possible – a view should know only the bare minimum it needs to know in order to do it’s job, and do bare minimum it has to do.

Here are 3 simple tips that can help us achieve this:
Continue reading

Testing Backbone + RequireJS Applications with Jasmine


In my previous post, I covered the structure of a Backbone.js application using RequireJS.
The next thing (or if you are a TDD fan, the first thing) we do is to run some tests on it.
According to Coda Hale:

Writing tests for your code may not reduce the number of bugs, but it will make fixing the bugs you inevitably find easier.

Obviously, we can take advantage of the AMD architecture, to help us write modular tests (or “specs” in the BDD language).
To get a better sense of the challenges and different approaches in unit testing, I wrote the exact same tests three times using three different testing frameworks: Jasmine, Mocha and QUnit.
Continue reading

Build Backbone Apps Using RequireJS

TodosBackbone gives us a very powerful set of tools. It gives us models, views, and routes – all event driven, consistent and beautifully embrace underscore.js functionality. Being a library rather than a framework, Backbone doesn’t give us application structure. That “glue” we need too initialize the app and glue all the pieces together.
Since coding is by far easier than explaining, I programmed a Todos app in order to demonstrate how this can be done with Asynchronous Module Definition (AMD) using RequireJS.
Continue reading

PubSub / Observer Pattern and Coupling

PubSub (or the observer pattern) is obviously the hottest pattern in client side development, and I would like to take a shot at trying to refine the best practices for using it in a flexible and robust way.

The definition provided in the original Gang of Four book on Design Patterns states:

“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically”

As in any design pattern, an important part is to keep the application loosely coupled and with high cohesion.
Continue reading

Backbone.js Poller

Lets say you have a Backbone.js based messaging system on your application, and you want to stay synced with the server so you could alert your users when a new message arrives. You would like to call the server once every couple of seconds and ask for status updates.
Or maybe your model represents an on going background task, you want to poll for status updates.
You could start with something basic such as:

function poll(collection, delay) {
  setInterval(function(){
    collection.fetch({data: {foo: 'bar'}});
  }, delay);
}

This works, but has some flaws:

  1. You may end up running simultaneous requests hitting the browser’s allowed connection per host limit (typically 6, 2 on IE7, according to browserscope)
  2. Nothing prevents you from running the function multiple time with the same collection
  3. You can’t easily stop the process, and abort running requests
  4. It doesn’t handle cases where we want to stop polling a model on a condition (say, when it’s task is done)

This may results in unnecessary load on the server side

You could run the next request only upon successful fetch request, and write something like this:

function poll(collection, delay) {
  collection.fetch({
    data: {foo: 'bar'},
    success: function(){
      setTimeout(function(){
        poll(collection, delay);
      }, delay)
    }
  });
}

This solves #1 bit doesn’t help other issues.
It takes a little more than that, and starts smelling like a special helper is needed.
You could add a poll() and unpoll() methods to your base models or collections using inheritance or mixin.
I wouldn’t like to promote such approach since it breaks the model’s interface and introduces tight coupling between the model and application state.
This easily becomes a slippery way down to maintenance hell.
A better pattern would be to use an external helper that will keep our interfaces clean and our models stateless and decoupled.

I ended up writing a Backbone Poller, A polling helper utility for Backbone.js.
a basic usage for our messaging system will could like

var inbox = new InboxCollection();
var poller = Backbone.Poller.get(inbox, {
    delay: 2000, 
    data: {sort: 'date desc'}
});
poller.on('success', function(){
    // do something on every successful fetch
});
poller.start();

A more advanced usage for our long going offline task could look like

var options = {
    delay: 2000,
    // when this becomes false the poller will stop
    condition: function(model){
        return model.get('done') !== true; 
    }
};

var task = new OfflineTaskModel();
var poller = Backbone.Poller.get(task, options);
poller.on('complete', function(){
    // task is done, do something
});
task.set('command', 'some-long-procedure');
task.save({},{
    success: function(){
        poller.start();
        
    }
});

The code and examples are available under the MIT license in github.

Backbone.js URI Sync Adapter

I am working on a backbone based search page, and was trying to figure out what would be a simple way to have both a state model and a URI that represents that state of the page (the search string, search parameters, user preferences, etc.).

Thinking of mixing backbone routes and the application models seemed like an overkill, and would force me to handle everything through a route or an event.

After a short struggle, I realized that the best case would be to have a model that keeps me in model land, but has the representation in the URI, and came out with Backbone URI Storage.

The concept is very simple, and works like charm – use a standard backbone model, enjoy data binding, and simply hook the model in the URI.

var State = Backbone.Model.extend({
    sync: uriSync
});
var Search = Backbone.Model.extend({
    url: '/rest/v1/search/';
});

And now, I can update the application state when my search changes:

var state = new State({id: 'search-page'});
var search = new Search();
search.on('change', function(){
    state.save(search.toJSON());
});

A working code example can be found here.

Its as simple as that!