6

Background

I have a long list of models and views made with backbone.js - but not all users will open all views. I use require.js to load JavaScripts files and templates.

What I have now

I have a router that knows about all views. Since the router know this, all views, models and templates are therefore loaded at startup - this also loads randomly visited views.

Problem

How can I use require.js to load the JavaScripts when needed? Not in the initial startup, but when user first opens a view.

UPDATE I can now get this working as commented in answer below.

In router I have a require per route:

require(["yourmodule"], function(MyModule){
    //...
})

1 Answer 1

5

This is a great guide for marrying Backbone.js and Require.js:

http://backbonetutorials.com/organizing-backbone-using-modules/

Sign up to request clarification or add additional context in comments.

6 Comments

In your router, you load your views - will require.js then load the full module graph? A view has a collection, and a collection again requires a model and so on. What I would like to know if I can load the module, when I actually need it
Have you tried something like this in your router handler? require(["yourmodule"], populateYourView)
@IntoTheVoid: Please note that the current version of jQuery, Underscore and the branch of Backbone include support for AMD so the integration with RequireJS is a lot simpler now. Have a look at updated example on backbonetutorial's github or check out a simple Backbone Project Template.
@IntoTheVoid There is a branch of Backbone.js that supports AMD, so you don't need to create any of those wrappers described in the tutorial. Just have a look at the links from my comments and you wil l see that almost nothing is required to integrate Backbone.js + Underscore and jQuery with RequireJS. You have it all there.
For anyone looking at a more in-depth example of backbone+require.js check out backboneboilerplate.com
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.