Backbone Model.set while mid-sync

I recently ran into an interesting problem when creating the UI for what amounted to a complex form. The page consisted of a number of inputs, many of which could trigger model.set or model.save calls when their values changed, as well as a background “auto save” feature which fires periodically.

The page consists of an <input> A and a <button> B. The Backbone model has two values which these values control: name and type. The default values are {name: null, type: 1}. Entering a value in input A triggers a model.save({name: inputA.val()}), whereas clicking on button B triggers model.set('type', 2).

The scenario I ran into looks like follows:

  1. User types “Hello World” in input A, triggering a model.save() call with a POST/PUT and a request body of {name: "Hello World", type: 1}.
  2. While the POST/PUT is still outstanding, the user clicks on button B, triggering a model.set('type', 2);. The model’s attributes now read {name: "Hello World", type: 2}.
  3. The POST/PUT returns, with a response body of {name: "Hello World", type: 1}. Since it has no knowledge that the model.set('type', 2) in step #2 has occurred, it immediately overrides type back to its original value of 1.

The UI may or not be listening for this change:type and will re-render or not accordingly when this happens. If it does re-render, the user has a jarring experience where their click on button B is immediately undone. If the View does not re-render on that change, a more subtle and dangerous problem manifests itself: if model.save() is again called, the user will be saving a type to the server that does not reflect what they see on their screen! Either way, it’s bad new bears.

Choices, choices…

There are several ways one might handle this scenario. For starters, you could simply disable the UI while the model is syncing. While this does prevent the bug from above from even occurring, the obvious downside is that the UI becomes briefly unresponsive, possibly even “flashing” as inputs toggle to disabled and back.

Another approach would be to have each input’s View check for any outstanding AJAX calls on the model, and wait until those complete before calling model.set. This approach could prevent the issue as described above, but it requires a lot of boilerplate code for each input, which isn’t ideal and should make any seasoned dev’s skin crawl.

Door number three

After pondering a while, I came up with a little utility to add a deferredSet method to Backbone.Model. The logic here is pretty simple: when model.deferredSet is called, it checks whether the model is currently in the middle of syncing, and if it is, it holds off on calling set until that request is finished. If the model isn’t syncing (hopefully the majority case!) it immediately defers to the good old model.set.

Here’s a quick example of deferredSet and how it differs from set:

var model = new Backbone.Model();

var xhr = model.save({a: 1, b:2}); model.set({b: 3}); console.log(model.toJSON()); //{a: 1, b: 3} 
xhr.then(function() { console.log(model.toJSON()); //{a: 1, b: 2} - b: 3 is lost! });

var xhr = model.save({a: 1, b:2}); model.deferredSet({b: 3}); console.log(model.toJSON()); //{a: 1, b: 3} 
xhr.then(function() { console.log(model.toJSON()); //{a: 1, b: 3} - b: 3 is preserved! });

The usage is pretty simple, but if you want to dig in a bit more, check out the spec.

118 thoughts on “Backbone Model.set while mid-sync

  1. 2018 Car Release Date

    It is perfect time to make a few plans for the long run and it’s time to be happy. I’ve read this publish and if I could I want to counsel you some interesting issues or suggestions. Perhaps you can write next articles regarding this article. I desire to read more issues about it!

    Reply
  2. Travel

    Hey, you used to write excellent, but the last few posts have been kinda boring… I miss your super writings. Past several posts are just a little bit out of track! come on!

    Reply
  3. Jobs & Career

    I intended to draft you a very little note to be able to give thanks again relating to the gorgeous secrets you’ve discussed above. It is really strangely generous with you to make freely what exactly most people could have offered for sale as an e book to earn some money for themselves, chiefly given that you could have done it if you decided. The things in addition served to provide a easy way to recognize that other people online have a similar dream just like my own to see a whole lot more in regard to this condition. I am sure there are some more enjoyable moments up front for individuals that scan through your website.

    Reply
  4. Business & Finance

    I would like to thank you for the efforts you have put in writing this web site. I’m hoping the same high-grade website post from you in the upcoming also. Actually your creative writing skills has encouraged me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

    Reply
  5. riddim

    Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!|

    Reply
  6. judi poker online

    My programmer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on a number of websites for about a year and am nervous about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress content into it? Any kind of help would be greatly appreciated!

    Reply
  7. Eric Moyd

    I do believe that a foreclosure can have a important effect on the applicant’s life. House foreclosures can have a 7 to decade negative influence on a applicant’s credit report. The borrower who’s applied for a home loan or any kind of loans as an example, knows that your worse credit rating can be, the more challenging it is to obtain a decent loan. In addition, it could affect any borrower’s capability to find a quality place to lease or rent, if that turns into the alternative homes solution. Thanks for your blog post.

    Reply
  8. cara main capsa susun

    Hi, I do think this is an excellent web site. I stumbledupon it ;) I will revisit yet again since I book marked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.

    Reply
  9. domino qiu qiu

    Woah! I’m really enjoying the template/theme of this site. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between superb usability and visual appearance. I must say you’ve done a amazing job with this. Also, the blog loads super fast for me on Safari. Excellent Blog!

    Reply
  10. Business

    I like what you guys are up too. Such intelligent work and reporting! Carry on the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site :).

    Reply
  11. Car Release Date Specs

    Woah! I’m really digging the template/theme of this website. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between user friendliness and visual appeal. I must say you’ve done a amazing job with this. In addition, the blog loads super quick for me on Safari. Excellent Blog!

    Reply
  12. stomatolog gorzow

    hello there and thank you for your information – I’ve certainly picked up something new from right here. I did however expertise a few technical points using this website, since I experienced to reload the site many times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and can damage your high quality score if ads and marketing with Adwords. Well I’m adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Make sure you update this again very soon..

    Reply
  13. Car Release Date Review

    Hi, I do think this is an excellent web site. I stumbledupon it ;) I am going to revisit yet again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help others.

    Reply
  14. Automotive

    I’m really impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it is rare to see a great blog like this one nowadays..

    Reply
  15. Business & Finance

    hello!,I like your writing very much! share we communicate extra about your article on AOL? I need an expert on this space to resolve my problem. Maybe that is you! Taking a look ahead to look you.

    Reply
  16. electronics

    hello there and thank you for your information – I’ve certainly picked up something new from right here. I did however expertise some technical points using this website, as I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and could damage your high-quality score if ads and marketing with Adwords. Anyway I’m adding this RSS to my e-mail and could look out for a lot more of your respective interesting content. Make sure you update this again soon..

    Reply
  17. renovation

    It¡¦s really a cool and useful piece of information. I am happy that you shared this helpful information with us. Please keep us up to date like this. Thank you for sharing.

    Reply
  18. Health

    Good – I should definitely pronounce, impressed with your website. I had no trouble navigating through all tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your customer to communicate. Excellent task.

    Reply
  19. Minikert

    we prefer to honor many other net web sites around the net, even though they arent linked to us, by linking to them. Underneath are some webpages worth checking out

    Reply
  20. Women

    I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again!

    Reply
  21. Career And Jobs

    I intended to draft you the bit of word so as to say thank you the moment again on your precious principles you’ve shown at this time. It has been quite wonderfully open-handed of people like you to offer without restraint just what a number of us could possibly have supplied for an e-book in making some profit for their own end, and in particular considering that you might well have tried it in case you wanted. These suggestions also worked like the great way to be sure that other individuals have the same zeal just as my own to grasp somewhat more with regards to this condition. I’m certain there are millions of more enjoyable times in the future for folks who read through your blog.

    Reply
  22. how to get free robux

    Woah! I’m really digging the template/theme of this site. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between user friendliness and visual appeal. I must say you’ve done a amazing job with this. In addition, the blog loads super quick for me on Internet explorer. Outstanding Blog!

    Reply
  23. Dr. Joseph Jensen

    “Hi there, just was aware of your weblog thru Google, and located that it’s truly informative. I’m going to watch out for brussels. I’ll be grateful for those who proceed this in future. Lots of other folks will be benefited out of your writing. Cheers!”

    Reply
  24. how to get free robux

    Woah! I’m really loving the template/theme of this blog. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between superb usability and visual appeal. I must say you have done a very good job with this. In addition, the blog loads very quick for me on Firefox. Outstanding Blog!

    Reply
  25. home improvement cast

    I simply couldn’t leave your site before suggesting that I actually enjoyed the usual info a person supply in your visitors? Is going to be back continuously to investigate cross-check new posts

    Reply
  26. pregnancy miracle book by lisa olson

    Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it develop over time.

    Reply
  27. Travel & Leisure

    Wow! This could be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Great. I am also an expert in this topic therefore I can understand your hard work.

    Reply
  28. Business & Finance

    I was just searching for this information for a while. After 6 hours of continuous Googleing, at last I got it in your web site. I wonder what is the lack of Google strategy that don’t rank this kind of informative sites in top of the list. Normally the top sites are full of garbage.

    Reply
  29. podnośnik koszowy wynajem lubin

    When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment. Is there any way you can remove me from that service? Thanks a lot!

    Reply
  30. Business & Finance

    Good site! I truly love how it is simple on my eyes and the data are well written. I’m wondering how I might be notified whenever a new post has been made. I’ve subscribed to your feed which must do the trick! Have a nice day!

    Reply
  31. House & Home Improvement

    I do trust all of the ideas you have presented on your post. They are really convincing and can certainly work. Still, the posts are too short for newbies. May just you please prolong them a bit from subsequent time? Thank you for the post.

    Reply
  32. como criar uma dieta

    Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between superb usability and appearance. I must say you’ve done a awesome job with this. In addition, the blog loads extremely quick for me on Firefox. Superb Blog!

    Reply
  33. Web Design

    I haven’t checked in here for a while as I thought it was getting boring, but the last few posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend :)

    Reply
  34. Automotive

    you are really a just right webmaster. The website loading pace is incredible. It kind of feels that you are doing any unique trick. Furthermore, The contents are masterpiece. you’ve performed a fantastic activity on this subject!

    Reply
  35. Article About Technology

    I not to mention my pals were taking note of the nice information located on your web site and so unexpectedly I had a terrible feeling I never thanked you for those techniques. Most of the people happened to be as a consequence happy to study all of them and have in effect clearly been using those things. Many thanks for actually being simply thoughtful as well as for opting for some perfect resources most people are really eager to learn about. My sincere regret for not expressing gratitude to you sooner.

    Reply
  36. Travel

    Great blog here! Also your website loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as quickly as yours lol

    Reply
  37. Health Plans

    It¡¦s truly a great and useful piece of information. I am happy that you just shared this useful information with us. Please stay us up to date like this. Thanks for sharing.

    Reply
  38. Home Product and Service

    Thanks for any other wonderful article. The place else could anyone get that kind of information in such an ideal way of writing? I’ve a presentation subsequent week, and I am on the search for such info.

    Reply
  39. Health and Fitness

    Undeniably believe that which you stated. Your favorite justification appeared to be on the net the simplest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people could take a signal. Will likely be back to get more. Thanks

    Reply
  40. Dating

    Keep up the great piece of work, I read few posts on this website and I believe that your web blog is really interesting and holds bands of wonderful information.

    Reply
  41. Home Product and Service

    naturally like your website but you have to test the spelling on quite a few of your posts. A number of them are rife with spelling issues and I find it very troublesome to inform the reality however I will surely come back again.

    Reply
  42. Health And Wellness

    I carry on listening to the news update lecture about receiving free online grant applications so I have been looking around for the most excellent site to get one. Could you advise me please, where could i acquire some?

    Reply
  43. BBC Sport News

    I was just seeking this info for a while. After six hours of continuous Googleing, finally I got it in your web site. I wonder what’s the lack of Google strategy that do not rank this type of informative websites in top of the list. Usually the top websites are full of garbage.

    Reply
  44. Dating

    I’ll right away take hold of your rss feed as I can not in finding your e-mail subscription hyperlink or e-newsletter service. Do you’ve any? Please permit me recognize in order that I may just subscribe. Thanks.

    Reply
  45. international business

    You actually make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand. It seems too complicated and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

    Reply
  46. technology current events

    I do consider all the ideas you’ve introduced on your post. They’re really convincing and will certainly work. Nonetheless, the posts are very quick for beginners. Could you please lengthen them a bit from next time? Thanks for the post.

    Reply
  47. Myles Buendia

    A few things i have constantly told men and women is that when looking for a good on-line electronics shop, there are a few elements that you have to factor in. First and foremost, you need to make sure to find a reputable and also reliable store that has enjoyed great assessments and scores from other buyers and business world analysts. This will ensure you are getting along with a well-known store that delivers good program and aid to its patrons. Many thanks for sharing your ideas on this website.

    Reply
  48. Dating

    Thank you so much for giving everyone an extremely memorable opportunity to discover important secrets from this web site. It really is very great and also full of a great time for me personally and my office fellow workers to visit your web site not less than thrice a week to learn the newest stuff you will have. And indeed, I am also always contented concerning the effective suggestions you give. Some 1 points in this article are undoubtedly the best we have had.

    Reply
  49. BobunVar

    Каждая современная нормальная женщина думает о отличной фигуре, так и всякий обычный мужчина, предпочтет супругу с ладным и прекрасным телом. В указанном окружению способствуют диеты. Однако следует не забывать, что избирать диету рекомендуется так, для того чтобы потом не повредить собственное дорогое здоровье.

    Подробнее диета при язве желудка

    Reply
  50. kegel balls

    Wonderful story, reckoned we could combine a handful of unrelated information, nonetheless seriously worth taking a appear, whoa did a single learn about Mid East has got additional problerms at the same time

    Reply
  51. business news

    I am very happy to read this. This is the type of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.

    Reply
  52. Business School

    I’m extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you modify it yourself? Either way keep up the excellent quality writing, it is rare to see a great blog like this one nowadays..

    Reply
  53. Business

    Attractive section of content. I just stumbled upon your blog and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently fast.

    Reply
  54. business ideas

    You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

    Reply
  55. Clothes Shopping Online

    I keep listening to the news bulletin talk about receiving free online grant applications so I have been looking around for the most excellent site to get one. Could you tell me please, where could i acquire some?

    Reply
  56. Terrell Birdsong

    I have been exploring for a little for any high quality articles or weblog posts in this kind of house . Exploring in Yahoo I finally stumbled upon this web site. Reading this info So i am satisfied to show that I’ve an incredibly just right uncanny feeling I came upon exactly what I needed. I so much unquestionably will make certain to do not omit this website and give it a glance on a constant basis.

    Reply

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *