What can cause a deferred object to be rejected?

I think I'm wrong. This is what I am trying to do, instead of using RequireJS or LABjs:

var APP = {}; APP._timers = {}; APP._timelines = {}; $.when( $.getScript('/app/models/Timer.js'), $.getScript('/app/models/Section.js'), $.getScript('/app/collections/Timers.js'), $.getScript('/app/collections/Sections.js'), $.getScript('/app/views/SectionView.js'), $.getScript('/app/views/APPView.js'), $.Deferred(function(deferred){ $(deferred.resolve); }) ).done(function () { alert('done'); console.log(APP.APPView); var foo = new APP.APPView; APP._timelines.main = new APP.Timers('main'); APP._timelines.branched = new APP.Timers('branched'); }).fail(function(){ alert('failed'); }); 

It warns failed , nothing is written to the console.

If I open any of these files, say APPView.js and warn something at the top or bottom of the file, I see that it is displayed. Here is an example of this file:

 APP.APPView = Backbone.View.extend({ el : $("#app-view"), initialize : function () { alert('App view initialized'); // Never gets called this.sectionVew = new APP.SectionView(); } }); alert('Inside APPView.js'); // gets called 
+4
source share
2 answers

I think the reason this happens is because you are trying to load all your scripts inside $.when without dependency management. Each of $.getScript is asynchronous, and they are not necessarily populated in order. Therefore, if your view is loaded before your model execution stops, when it tries to use the undefined model. In short, for this you will have to either:

  • Manage dependencies manually. those. after loading the model, THEN loads the view.
  • write network-independent modules
  • and this is the simplest, stop trying to manually do all this and use an AMD loader like require.js. That's why he is there!
+2
source

I'm not sure about the implementation of your domReady deferred, try it like this:

 var APP = {}; APP._timers = {}; APP._timelines = {}; var domRdyDeferred = $.Deferred(); $(domRdyDeferred.resolve); $.when( $.getScript('/app/models/Timer.js'), $.getScript('/app/models/Section.js'), $.getScript('/app/collections/Timers.js'), $.getScript('/app/collections/Sections.js'), $.getScript('/app/views/SectionView.js'), $.getScript('/app/views/APPView.js'), domRdyDeferred ).done(function () { alert('done'); console.log(APP.APPView); var foo = new APP.APPView; APP._timelines.main = new APP.Timers('main'); APP._timelines.branched = new APP.Timers('branched'); }).fail(function(){ console.log(arguments); alert('failed'); }); 

It is important to note that they may not end in the order in which you add them to $.when

+1
source

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


All Articles