Search code examples
backbone.jsbackbone-stickit

Stickit: How to trigger a change event after every model -> view change


I have many events bound to elements in my view, though when I use stickit js to change values in my view by altering the model it doesn't trigger an onChange event.

Is there a way that I can trigger an onchange event for the current model:element after the setting the value in the model without having to write a handler for every binding? This would be for all form elements, input/select/textarea.

I want to avoid the following for each form element on the page:

bindings: {
    '#foo': {
         observe: 'foo',
         afterUpdate: 'forceChange'
    },
    '#bar': {
         observe: 'bar',
         afterUpdate: 'forceChange'
    },
    ...
},

forceChange: function(el) { jQuery(el).change() }

Solution

  • One possible hack (with version 0.6.3 only) would be to define a global handler which matches all elements:

    Backbone.Stickit.addHandler({
      selector: '*',
      afterUpdate: function($el) {
        $el.trigger('change');
      }
    });
    

    Since handlers are mixed in with other matching handlers and bindings configurations in the order that they are defined, you couldn't use afterUpdate in any of your bindings without overwriting this global, all-matching handler since the bindings configurations are the last to be mixed in. You can read more about it here.