Search code examples
backbone.js

Trigger backbone.js change when value doesn't change


It's a known feature of backbone.js that when you set data that hasn't changed it won't fire the change event, nor will it go through validations. I however need the change event to fire as I'm storing a JSON response from an AJAX call which stores results of backend validation. If the user keeps submitting the form while leaving the same field empty, the backend validation will return the same JSON result and when I save it to the model it won't trigger the change event.

A few things I've tried within the AJAX success callback where I set the data into the model:

Attempted Solution #1

t.model.unset('fieldErrors',{silent: true});
t.model.set({fieldErrors: JSONResponse});

Attempted Solution #2

t.model.set({fieldErrors: null},{silent: true});
t.model.set({fieldErrors: JSONResponse});

Neither of these results in the change event firing a second time when the call is made and the user has the same JSONResponse.


Solution

  • Manually trigger the change event:

    t.model.trigger('change', t.model);
    

    or

    t.model.trigger('change:fieldErrors', t.model, newFieldErrorsValue);