Wikipedia

Search results

07 August 2014

Delegate pattern with Backbone.js

Backbone.js comes with a built-in Event handler, known as Backbone.Events whose implementation is described well in the LosTechies article found here.

However, the pattern is really known as Aggregation pattern; and a method in one view controller can be invoked within another view controller.

The reason it is not readily a delegate pattern deals with the issue of scope respective to Javascript. The view controller who invoked the method of another view controller does so within their own scope, and local variables are then not recognized:

// viewcontroller 1
vent.trigger('foo')

// viewcontroller2
foo: function() {
  console.log('this.foobar', this.foobar)
}

// console
this.foobar unknown


In order to make the view controller able to reference values local to itself, a small modification can be made to the traditional `bind` of the Backbone.Events variable:

this.vent = Backbone.Events('foo', function() {
  this.foo();
});

Here, the anonymous function references the function within the scope of the original view controller. Now when the same code is run, the output will be the value of `this.foobar`. Run delegate pattern with Backbone.js using Backbone.Events!

1 comment: