Search code examples
javascriptangularjsbackbone.js

How to know when model has changed on front side with Backbone?


I probably don't understand some of the Backbone logic and so hope you can explain it to me.

When I create a model, pass it an ID and then fetch it, Backbone marks the model as changed (a call to changedAttributes() returns all the object attributes).

When you modify an object attribute on front side, it also marks the model as changed with only this attribute being returned by changedAttributes().

So how do you make a difference between changes made on front-side (and so, not persisted) and changes which comes from the server ? (Is there any specific events ?)

The reason for why I'm asking this is that I'd like to save my model, times to times, if there are some front side changes or if the user quits.

[edit] My scenario is (I work with Angular):

The URL of my page is of the form: object/#/:id

My page is an editor for the object (some inputs).

When the ID in the URL changes, I fetch the corresponding object from the server. But if there were already something (like if the user manually changes the ID), I need to save whatever has been done on the object first.


Solution

  • There is no real tracking of model/collection changes in Backbone, that tells you what or if something changed. You have to do this by yourself.

    You can of course check the changes of the current change loop. So in an event handler you use like model.on("change", () => ...). You might want to implement a handler function, that tracks the change, and maybe reset it, after you saved it on the server