Search code examples
backbone.jsrequirejs

Requirejs for Backbonejs application


I want to use Requirejs to run a Backbonejs application. Here is my basic setup.

root/
root/index.htm
root/scripts/
root/scripts/require-jquery.js
root/scripts/order.js
root/scripts/main.js
root/scripts/app.js
root/scripts/app.build.js
root/scripts/backbone.js

index.htm

<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<div id="home"></div>

main.js

require([
    "order!http://documentcloud.github.com/underscore/underscore.js",
    "order!backbone",
    "order!app"
    ],function(_,Backbone,app){
    app.init();
});

app.js

define(["jquery","underscore"],function($,_){
    var init = function(){
        var arr = ['orange','apple','bannana'];
        _.each(arr,function(fruit){
            console.log(fruit);
        });
    };

    return { init: init };
});

backbone.js

define(["order!http://documentcloud.github.com/backbone/backbone.js"], 
    function(){
        return Backbone;
}); 

I haven't gotten to the Backbone stuff yet because I am running into an error with this current setup...

Line 150: _ is undefined at _.extend(Backbone.Model.prototype, Backbone.Events, {

I am trying to make this thing as simple as possible and be able to eventually add my routers, models, etc...And build the thing down the road...

What am I missing here in my setup to get this thing rocking?

Also, would it be better in any way to use local js files instead of trying to load things from CDNs?


Solution

  • The following might be helpful:

    Requirejs' order does not work with priority config and CDN dependencies

    In short, require doesn't work perfectly with CDN assets and order.js--you have to nest your require calls (which kinda stinks).

    Normally I've used local copies of backbone and underscore and they've worked well with the order! plugin