简体   繁体   English

骨干:构造函数在文件中的位置

[英]Backbone: location of constructor in file

I have a pretty basic Backbone app which uses a router to instantiate views and collections. 我有一个非常基本的Backbone应用程序,该应用程序使用路由器实例化视图和集合。 In playing around with the app, I noticed that if I put the line of code instantiating the router 在玩这个应用程序时,我注意到如果我放置代码行来实例化路由器

 router = new DocsRouter();

at the top of the application.js file, then the app didn't work; 在application.js文件的顶部,则该应用程序无法运行; it had to be at the bottom of the file. 它必须在文件的底部。 Yet, this didn't make sense to me. 但是,这对我来说没有意义。 Why should the location of this line of code matter, since everything important to start the app happens inside the router? 为什么这行代码的位置很重要,因为启动应用程序的所有重要操作都发生在路由器内部? Shouldn't I be able to trigger the router from anywhere? 我不应该可以从任何地方触发路由器吗?

 window.DocsRouter = Backbone.Router.extend({

        initialize : function() {

            this.docs = new Docs();

            this.docs.fetch();


            this.docFormView = new DocFormView({ collection : this.docs });
            this.docsView = new DocsCollectionViewTempo({ collection : this.docs });
            this.docsView.render();

            this.route("doc/:id", "doc", function(id){
                console.log(id, this.docs.get(id).toJSON());
            });
        },

        routes : {
            "" : "root",
            "about" : "about",
            "doc/:id" : "doc"
        },

        root : function() { console.log('Vous êtes à la racine');},
        about : function() { console.log('A propos : ceci est un tutorial BackBone');},
        doc : function(id) { console.log(id, this.docs.get(id).toJSON()); }
    });

 router = new DocsRouter();
 Backbone.history.start();

No. You cannot create an instance of DocRouter before DocRouter has been declared. 不可以。在声明DocRouter之前,您无法创建DocRouter的实例。

window.DocsRouter = Backbone.Router.extend({..});
router = new DocsRouter();

The order of these two lines has to be this. 这两行的顺序必须是这个。 Before the first line DocRouter does not exists thus you can not instantiate it. 在第一行DocRouter不存在之前,因此无法实例化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM