Gambo
Gambo

Reputation: 1572

Models/View in Different Files

I just tried to adopt backbone.js to my project with the todo example. In my app.js file I try to instantiate my views/models/collections etc. but I try to I get the error msg: app is not defined in TodoList.

HTML:

<head>

<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/underscore-min.js"></script>
<script type="text/javascript" src="js/backbone-min.js"></script>
<script type="text/javascript" src="js/backbone-localstorage.js"></script>

<script type="text/javascript" src="js/models/models.js"></script>
<script type="text/javascript" src="js/collections/collections.js"></script>
<script type="text/javascript" src="js/views/views.js"></script>
<script type="text/javascript" src="js/views/app.js"></script>

<script type="text/javascript" src="js/app.js"></script>

app.js(root for my application):

    var app = {
    models:{},
    collections:{},
    views:{}
};

    jQuery(function($) {

        var Todos = new app.collections.TodoList;
        var test = new Todo;
        var test2 = new TodoView;
        var appView = new AppView({});

    });

collections.js:

app.collections.TodoList = Backbone.Collection.extend({

model: Todo,

localStorage: new Store("todos"),

done: function() {
    return this.filter(function(todo) {
        return todo.get('done');
    });
},

remaining: function() {
    return this.without.apply(this, this.done());
},
nextOrder: function() {
    if (!this.length) return 1;
    return this.last().get('order') + 1;
},

comparator: function(todo) {
    return todo.get('order');
}

});

Upvotes: 3

Views: 1737

Answers (1)

Stephen
Stephen

Reputation: 5460

You're trying to use a namespace before it's ready. Two options. First, have 'app.js' first but take out initialization code and put that into a 'bootstrap.js' that's loaded absolute last. Second option, and the one that I generally lothe, define your namespaces that you need in the file if they aren't already there. For example

var app = app || {};
app.collection = app.collection || {};

Basically, the code is loading in one by one. When you say namespace.subspace, the code expects that namespace has already been defined as something - generally an object in most cases that I've seen. Without that base piece the code will just flatline - it'll assume you're trying to do the equivalent of building a castle starting with the roof.

Upvotes: 5

Related Questions