Question

I'm trying to add localstorage to my collections in backbone.js, but for some reason, require.js wont load it.

Here's what is in the main.js file that requirejs loads:

require.config({
  paths: {
    'jquery': 'libs/jquery/jquery-1.7.1.min',
    'underscore': 'libs/underscore/underscore-min',
    'backbone': 'libs/backbone/backbone-min',
    'backbone-localstorage': 'libs/backbone-localstorage/backbone-localstorage-min',
    'text': 'libs/require/text'
  }
});

You can see the full source at https://github.com/tominated/Vendotron. I can tell it's not loading because when I put the localstorage snippet into my collection, it errors out in chrome's console saying that Store isn't defined.

Any idea what I'm doing wrong?

Was it helpful?

Solution

There are a couple problems.

First, you are setting the path to backbone-localstorage, but you are never requiring it anywhere, so it is never actually loaded. Setting that path is basically defining a shortcut to it, not loading it.

The second problem is that, like backbone itself, most backbone plugins are not AMD modules. They want to have Backbone loaded first, so they can add their extensions to it.

It looks like you are using an AMD fork of Backbone, but not backbone-localstorage. You could try to find an existing one, or make your own similar to this.

Either that, or you can try to load backbone-localstorage as-is (adding to the dependencies list of your define call), but you would need to use the !order plugin to make sure backbone is loaded first.

OTHER TIPS

As Paul said, you are not requiring the localstorage module anywhere. Require.js 2.0 has a specific mechanism for JavaScript code that is essentially a plugin for other code - the shim option. Including localStorage would look like this:

require.config({
  baseUrl: "/js/",
  paths: {
    jquery: 'lib/jquery-1.8.0',
    underscore: 'lib/underscore-1.3.3',
    backbone: 'lib/backbone-0.9.2',
    'backbone.localStorage': 'lib/backbone.localStorage'
  },
  shim: {
    underscore: {
      exports: "_"
    },
    backbone: {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone'
    },
    'backbone.localStorage': {
      deps: ['backbone'],
      exports: 'Backbone'
    }
  }
});

This example was copied from the article "Build Backbone Apps Using RequireJS" which also explains how to structure your code and how to compile the code into one file when deploying the application.

On looking inside the source code, where underscore and backbone are required, your path definition in require config should tally with the required path in local storage I.e case sensitive

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top