crawf
crawf

Reputation: 9658

Require.js loading Backbone views in order

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?

Upvotes: 0

Views: 1725

Answers (1)

nikoshr
nikoshr

Reputation: 33344

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();
    }   
});

Upvotes: 1

Related Questions