Backbone.js: separate view, collection, model from different js files, they cannot recognize each other

I use Backbone.js to create a web application, all views, collections and models are written in one js file, it is a success!

Now I want to split them into different js files, like:

<script type="text/javascript" src="js/layermanagemodel.js"></script>       
<script type="text/javascript" src="js/layermanagecollection.js"></script>  
<script type="text/javascript" src="js/layermanageview.js"></script>    
<script type="text/javascript" src="js/boot.js"></script>

and load the model code in jquery download:

$(function(){
    //Model
        var manageModel = Backbone.Model.extend({
                default:{
                    'selectedId':'unknow'
                },
                selectLayer:function(uuid){
                     this.set({"selectedId": uuid});
                },
                delLayer:function(){

                }
        }); 
})

but firebug will tell me an error:

manageModel is not defined
[Break On This Error]   

model: manageModel

in the collection file

why, if they split them into different files, they cannot recognize each other? How can I solve this problem? Or what is the correct boot order? thank

+5
source share
2 answers

After adding function wrappers:

$(function() {
    // ...
})

, var, , . , (.. window):

$(function(){
    window.manageModel = Backbone.Model.extend({
        //...
    });
});

, :

$(function(){
    window.app = window.app || { };
    window.app.manageModel = Backbone.Model.extend({
        //...
    });
});

app app.manageModel:

$(function(){
    window.app = window.app || { };
    window.app.someCollection = Backbone.Collection.extend({
        model: app.manageModel,
        //...
    });
});
+9

, js , Require.js. , , . , . . backbone.js :

define([
    'jquery',
    'underscore',
    'backbone',
    'models/post'
], function ($, _, Backbone, Post) {
    "use strict";
    var PostsCollection = Backbone.Collection.extend({
        model: Post,
        url: CONFIG.apiUrl + 'posts'
    });
    return PostsCollection;
});

. , "models/post" . jquery, underscore backbone , , . , js , Require.js, .

+3

All Articles