Search code examples
javascriptbackbone.jsmarionettebackbone-events

Deferred objects VS backbone events for View updates in Marionette


I am learning Marionette / Backbone with the excellent book "Backbone.Marionette.js: A Gentle Introduction". In the chapter 'Handling Data Latency', the Author (David Sulc) uses JQuery deferreds objects / promises to pass data from the fetch() action (called in entities/contact.js) to controllers (show_controller.js and list_controller.js in the example).

Code is available here : https://github.com/davidsulc/marionette-gentle-introduction/commit/de25497a1fa028f6a4471b0003645307a6e426f8

I understand how it works but in my previous readings on Backbone, this kind of thing was handled by Backbone events: we listen to a 'change' event on the model and we call render() when it is triggered. So I have a few questions about that :

1/ Are deferred objets better than backbone events for updating the view when we get a response from the server?
2/ What are the pros and the cons of the 2 solutions?
3/ Is it wrong / bad design to use backbone events in this situation?

Thanks for your help!


Solution

  • A specific use-case would be where you want to load/instantiate a view only when a model/collection has been fetched from the server. In that case you can use the Deferred object because that'll tell you exactly when the data has been loaded.

    Of course you can listen to a change event on the model/collection, but you'd need to have a view instantiated already or add an extra listener to your model/collection to create the view.

    So, to answer your questions:
    1. Really depends, if you don't mind updating your view, then events are fine. If you want to instantiate a view later on, deferreds are a good fit.

    2. See introduction

    3. Not really. It also depends on the scale of your application. As S_I_R mentiones as well, it'll probably result in a bit cleaner code.