janmonschke/backbone-couchdb — pull request #25 by ahamid (2011-11-14 03:17:43+00:00)
Title: Support for single global changes feed

This patch adds support for a single global changes feed (it also includes my previous patch for conservative collection name derivation, although that is trivial to separate).

The global feed is enabled like:

Backbone.couch_connector.config.single_feed = true;

When the single global feed is enabled, the way collection change handlers are registered is changed. (_Whether_ they are registered has not been changed, and is still governed by the `global_changes` or individual collection `changes` setting.)

When single feed is enabled, each collection handler will be registered with a single changes feed.

Each collection also supports a `local_filter` irrespective of the single feed. This `local_filter` function can be used to, you guessed it, filter change results from the changes feed. When coupled with the single changes feed this allows each collection to only observe relevant changes. When single feed is enabled, a default local filter is installed which does this (so if you follow standard conventions you should be able to just enable `single_feed`).

Default single_feed local_filter:

# default local filter which selects documents of a given collection
filter_collection : (results, collection_name) ->
entry for entry in results when (entry.deleted == true) || (entry.doc?.collection == collection_name)

Example of custom local_filter:

var NoteList = Backbone.Collection.extend({
url : "/notes",
model: Note,
db: {
local_filter: function(results) {
return _.filter(results, function(entry) { entry.doc.importance == "urgent" });
}
}
});

On a technical note, change listener registration could probably be factored out into a separate class that is reused for both the per-collection and global feed, but I wanted my changes to be minimal.