Note that there are some explanatory texts on larger screens.

plurals
  1. POwaiting till an on change handler is complete before saving model
    text
    copied!<p>I have a User model(Backbone.js) and I want to update its settings attribute and then save it to the server. Settings is in JSON format, and the way I have it set up is that settings is the string version and settingsJSON is the object version. I bind functions to the change event of each so that when one changes, it updates the other. </p> <p>The problem I am having, is that the save method is running before the changed handler is finished running. Is there any way i could ensure that all event handlers for that model are complete or something like that?</p> <p>how I'm calling it:</p> <pre><code>currentUser.get('settingsJSON').apps = appsEnabled; currentUser.save(); </code></pre> <p>My event handlers:</p> <pre><code>Initialize: function() { var that = this; this.on("change:settingsJSON", function(model){ model.set({settings: JSON.stringify(model.get('settingsJSON'))}); }); this.on("change:settings", function(model){ model.set({settingsJSON: JSON.parse(model.get('settings'))}); }); } </code></pre> <p>@fencliff:</p> <p>The change event is firing when I run this and works properly, I had it print the new settings string to the console. </p> <p>Are you sure that they are called synchronously? I added <code>console.log('changed')</code> to the end of the <code>.on(change)</code> and put <code>console.log('saved')</code> directly after <code>currentUser.save()</code> and every time the console read:</p> <pre><code>saved changed </code></pre> <p>For now I have just made it so that I stringily the JSON and save it to settings directly before I save and that works fine.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload