Skip to content
Brendan Saunders edited this page Apr 8, 2014 · 3 revisions

A Change Delegate is an object, inheriting from sudo.Base, that removes the need for the boilerplate code normally associated with handling the changeRecord objects returned from an observed Model.

###filter(changeRecord)

The lone method exposed by a Change Delegate, filter is intended to be bound as the callback when calling observe on a Model. The changeRecord passed to filter is inspected for a match (see filters below) and if found assembles and passes a 'data object' with the following properties to the specified method on the delegator:

{
  type: changeRecord.type,
  name: changeRecord.name,
  value: changeRecord.object[changeRecord.(name | path)],
  oldValue: changeRecord.oldValue,
  object: changeRecord.object
}

###filters

A hash of key:value pairs expected to be accessible by the delegate at this.data.filters. Remember, any arg passed to the delegate's constructor will be set as this.data. The format of the object should be:

{
  foo: 'bar',
  'baz.qux': 'vot'
}

In the filter function, if a match is found between a key and changeRecord.name a method on the delegator with a name matching filters[changeRecord.name] will be called, bound to the scope of the delegator, passed the assembled 'data object'.

###In Use

A typical pattern would be to instantiate the Delegate from a delegator in its construction step (though it can be done anywhere):

var Foo = function(el, data) {
  this.construct(el, data);

  // establish your delegate
  this.addDelegate(new sudo.delegates.Change({
    filters: {
      bar: 'handleBar',
      'baz.qux': 'handleBazQux'
    }
  }));

  // observe a model instance but delegate
  // the job of inspecting the changeRecord
  someModel.observe(this.delegate('change', 'filter'));
};

Foo.prototype = $.extend(Object.create(sudo.View.prototype), {
  handleBar: function handleBar(data) {
    // do something with data.value
  },
  handleBazQux: function handleBazQux(data) {
    // do something with data.value
  }
});
Clone this wiki locally