Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Not Defined

I have a Backbone app that gets errors of Backbone is not defined non-deterministically from different spots in my code that use Backbone. Sometimes it loads first and the site loads, other times it doesn't. I'm using the following as my main.js:

require.config({
  paths: {
    jqueryui: 'libs/jquery/jquery-ui',
    underscore: 'libs/underscore/underscore-min',
    backbone: 'libs/backbone/backbone-min',
    text: 'libs/require/text',
    order: 'libs/require/order',
    searchcollector: 'libs/jquery/searchcollector.plugin',
    guiders: 'libs/jquery/guiders'
  },
  shim: {
    'underscore': {
      exports: '_'
    },
    'backbone': {
      deps: ['underscore'],
      exports: 'Backbone'
    }
  }
});

require([
  'views/app',
  'helpers'
], function(app) {
  var app = window.app = new app();
});

I'm using

<script data-main="/assets/js/main" src="/assets/js/libs/require/require-jquery.js"></script>

in my HTML so jQuery is loaded with the require. I took this advice from this (http://stackoverflow.com/questions/8131265/loading-backbone-and-underscore-using-requirejs) SO thread, but nothing seems to be working. Shouldn't the Shim be loading the Backbone first and then making it globally available? Any help appreciated.

like image 724
eipark Avatar asked Feb 28 '26 20:02

eipark


1 Answers

Not sure if this is the correct answer but I've noticed that you don't list jquery as a Backbone dependency. While Backbone lists Underscore as the only hard dependency, Backbone.View will need jquery or zepto to work.

But why then, does it seem to work some of the time?

It might be that since jQuery is an AMD module, when you load, it sometimes loads first, and other times it doesn't. When it loads before Backbone, it is available and Backbone is happy. Otherwise, perhaps, the bad results you are getting.

Try something like this:

In your path add this:

jquery: 'libs/require/require-jquery'

And in your shim, add this:

'backbone': {
  deps: ['underscore', 'jquery'],
  exports: 'Backbone'
}

Let me know what you get as a result. I've never used the shim feature of requirejs2.0 so I'm curious whether I'm understanding the deeper stuff correctly.

like image 87
jmk2142 Avatar answered Mar 02 '26 14:03

jmk2142



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!