Question

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() }
Was it helpful?

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.

OTHER TIPS

Ahhh, that comment clarifies matters. So, in Javascript when you change an input's value "manually" (whether through jQuery or through someElement.value =) the browser won't, as you noticed, fire a change event. Change events (and most other events for that matter) are only fired in response to user actions, not to Javascript.

Luckily, just as you can "manually" change a value, you can also "manually" trigger an event. In jQuery the syntax for that is:

$(yourElement).trigger('change');

If you need to control things like e.target you can read up on the jQuery trigger documentation for the details, but that's the basic idea.

You can even chain the value-changing and event-triggering together if you want:

$(yourElement).val('newValue').trigger('change');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top