AesopWaits
AesopWaits

Reputation: 171

Require js and backbone

I'm getting a backbone is undefined error when trying to apply require js to my code. I've read other articles on the site saying to use shim and it did not resolve the issue.

helper/util.js:

require.config({

waitSeconds: 10,
paths: {
    "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min",
    "underscore": "http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min",
    "backbone": "http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min"
},
shim: {
    jquery: {
        exports: "$"
    }, 
    underscore: {
        exports: '_'
    },
    backbone: {
        deps: ["underscore","jquery"],
        exports: "Backbone"
    },
    app: {
        deps: ["backbone"],
        exports: "App"
    }
}

});
require(["Scripts/jquery.flip.min.js"]);
require(["Scripts/jquery-ui-1.10.2.custom.min.js"]);
require(["Scripts/RatingProviders.js"]);

main.js:

require(["helper/util"], function(App) {
    //Models
     TestProvider = Backbone.Model.extend({
        defaults: {
            ID: '',
            Name: '',
        },
        initialize: function() {
            this.ID= '';
            this.Name= '';
        }
    });
});

Upvotes: 0

Views: 397

Answers (2)

Loamhoof
Loamhoof

Reputation: 8293

All in all, your file doesn't make much sense. Here you are defining a class, so you should use the define function.

define(["helper/util"], function(App) {

You're not using the App var, so let's remove it:

define([], function() {

Now, we want to include Backbone (see Nirazul's answer for the shim explanation) to be sure that it's loaded. Also, Backbone will be a global var, so you're not required to declare it in the argument list:

define(['backbone'], function() {

Now, you have to return your new class:

return TestProvider = Backbone.Model.extend({

Also, for your jQuery plugin, you can also change some things. First, declare them in require.config (specify jQuery as a dependency in shim). Then, add them as dependencies to whatever class that requires them. That way, you're loading them asynchronously when they are actually needed.

Upvotes: 2

nirazul
nirazul

Reputation: 3955

My educated guess would be that you never actually require Backbone.

Try to require it like that:

require(["helper/util", "Backbone"], function(App) {
    //Models
     TestProvider = Backbone.Model.extend({
        defaults: {
            ID: '',
            Name: '',
        },
        initialize: function() {
            this.ID= '';
            this.Name= '';
        }
    });
});

Shim config tells the loader what to do when Backbone is part of a module's requirement but isn't actually an AMD Module.

Upvotes: 2

Related Questions