0

I'm having issues loading a collection of Backbone Views with RequireJS - as they aren't loading in the correct order.

Below is a simple example of what I am trying to achieve - a page loops through a collection of widgets, and, using its 'template' attribute, get its Backbone View. Its crucial that these are displayed in order, and they are currently being displayed in random order.

page.js

collection.each(function(widget) {
    require(['order!views/widgets/' + widget.get('template')], function(WidgetView) {
        WidgetView.render();
    })
}

widgets/widgetView.js (generic view)

define(['underscore','backbone'], function(_, Backbone) {
    var WidgetView = Backbone.View.extend({
        render: function() {
            // .. show view
        }
    });
   return WidgetView;
});

I'm aware of the order! plugin for RequireJS, but it doesn't seem to be doing its job. Is there something that I'm doing wrong?

crawf
  • 9,448
  • 10
  • 33
  • 43
  • Check out the accepted answer on https://stackoverflow.com/questions/8131265/loading-backbone-and-underscore-using-requirejs I think it is what you are looking for :) – PJUK Apr 06 '12 at 11:29

1 Answers1

1

As far as I can tell, issuing multiple require calls will fetch the dependencies in asynchronous mode. You probably need to build an array of the views and only then require them. For example,

var widgets=[];
collection.each(function(widget) {
    widgets.push('order!views/widgets/' + widget.get('template'));
});

require(widgets, function() {
    var viewclass, view;
    for (var i=0, l=arguments.length; i<l; i++) {
        viewclass=arguments[i];
        view=new viewclass();
        view.render();
    }   
});
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • Ah, that makes sense. However, it seems that I'm getting an error calling 'arguments', with the error being 'Object function (){a.apply(this,arguments)} has no method 'render'. – crawf Apr 06 '12 at 23:48
  • @crawf My example lacked the instantiation of the view. Updated my answer, it should work now – nikoshr Apr 07 '12 at 07:26
  • Doh! I should have known that..That worked a treat by the way - thanks so much for your help! – crawf Apr 07 '12 at 09:40