Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js:separate the view ,collection,model to different js file,they could't recognize each other

I use Backbone.js to create a web app,all the view,collection and model write into one js file,it success!

now I want separate them to different js files,just 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 model code in jquery load:

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

                }
        }); 
})

but the firebug tell me bug:

manageModel is not defined
[Break On This Error]   

model: manageModel

in collection file

why if separate them to different file ,they could not recognize each other?how can I solve this problem?Or what is right load order?thank you

like image 722
hh54188 Avatar asked May 18 '12 03:05

hh54188


1 Answers

Once you add the function wrappers:

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

You've introduced new scopes and all the vars declared inside those functions are only visible within those functions. You can get around this by making them global (i.e. properties of window):

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

or better, introduce an application namespace:

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

and then refer to things through app like app.manageModel:

$(function(){
    window.app = window.app || { };
    window.app.someCollection = Backbone.Collection.extend({
        model: app.manageModel,
        //...
    });
});
like image 148
mu is too short Avatar answered Oct 17 '22 01:10

mu is too short