Multiple Baseline Sampling

Is there a sexier way to do the following:

scheduleSubjects.fetch({ success: function(){ subjectList.fetch({ success: function(){ assignments.fetch({ success: function(){ _this.render(); } }); } }); } }); 

I want all the data to be extracted before I start manipulating it.

Thanks.

+6
source share
4 answers

Using jQuery pending objects , you can use $.when to call a callback when several asynchronous calls are completed:

 $.when(scheduleSubjects.fetch(), subjectList.fetch(), assignments.fetch()).then(_this.render); 

Note that this works because JQuery.ajax , and therefore Backbone.fetch , returns a pending object.


An alternative to .then is .done , which passes you the parameters of the original callbacks (which you don't need in the OP, but you can in some cases):

 $.when(scheduleSubjects.fetch(), subjectList.fetch(), assignments.fetch()) .done(function(scheduleSubjects, subjectList, assignments) { _this.render(); }) ); 
+8
source
 var collections = [scheduleSubjects, subjectList, assignments]; var complete = _.invoke(collections, 'fetch'); $.when(null, complete).then(function(){ _this.render(); }); 

use Promises and Underscore _.invoke() !

+7
source

You can use promises:

 scheduleSubjects.done(function () { subjectList.fetch(); }); subjectList.done(function () { assignments.fetch(); }); assignments.done(function () { _this.render(); }); scheduleSubjects.fetch(); 

or event listeners:

 subjectList.listenToOnce(scheduleSubjects, 'sync', subjectList.fetch); assignments.listenToOnce(subjectList, 'sync', assignments.fetch); this.listenToOnce(assignments, 'sync', this.render); scheduleSubjects.fetch(); 

You do not need to define these listeners within the view. they can live at the application level. The only thing that draws attention is the visualization when assignments retrieved

+2
source

The only way I can do this is with the bind() and trigger() baseline.

With events, you can achieve this functionality. Not sure if there is a better way. Once you have downloaded your first collection, you can start downloading the second. Theoretically, the two collections should not be combined in your example. The event-based load will be separated by subjectList and scheduleSubjects .

0
source

Source: https://habr.com/ru/post/956440/


All Articles