在加载主布局之前查看加载 [英] View loading before main layout is loaded

查看:45
本文介绍了在加载主布局之前查看加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自骨干模板的后续问题:"this.model is undefined".我能够算出一些结构,但是遇到了一个新问题.我正在使用主干样板,该主干样板使用layoutManager适配器设置视图.主视图以及随后的第一个视图似乎正在正确加载所有资产,尽管后视图在加载主视图之前似乎正在触发.这是我的路由器文件:

This is a followup question from Backbone boilerplate: "this.model is undefined". I was able to work out some of the structure, but have run into a new problem. I'm using backbone boilerplate, which uses the layoutManager adapter for setting the views. The main view, as well as the subsequent first view, seems to be loading all of the assets correctly, though the subsequent view seems to be firing before the main view gets loaded in. Here is my router file:

define([
    // Application.
    "app",

    //Modules
    "modules/homepage"
],
    function (app, Homepage) {
        "use strict";

        // Defining the application router, you can attach sub routers here.
        var Router = Backbone.Router.extend({
            initialize: function(){
                var collections = {
                    homepage: new Homepage.Collection()
                };

                _.extend(this, collections);

                app.useLayout("main-frame").setViews({
                    ".homepage": new Homepage.Views.Index(collections)
                }).render();
            },

            routes:{
                "":"index"
            },

            index: function () {
                this.reset();
            },

            // Shortcut for building a url.
            go: function() {
                return this.navigate(_.toArray(arguments).join("/"), true);
            },

            reset: function() {
                // Reset collections to initial state.
                if (this.homepage) {
                    this.homepage.reset();
                }

                // Reset active model.
                app.active = false;
            }

        });

        return Router;
    }
);

这是我的模块:

define([
    "app",
    ["localStorage"]
],
function(app){
    "use strict";

    var Homepage = app.module();

    Homepage.Model = Backbone.Model.extend({

        defaults: function(){
            return {
                homepage: {}
            };
        }
    });

    Homepage.Collection = Backbone.Collection.extend({
        //localStorage: new Backbone.LocalStorage("Homepage.Collection"),

        refreshFromServer: function() {
            return Backbone.ajaxSync('read', this).done( function(data){
                console.log(data);
                //save the data somehow?
            });
        },

        /*model: Homepage.Model,*/

        cache: true,

        url: '/app/json/test.json',

        initialize: function(options){
            if (options) {
                this.homepage = options.homepage;
            }else{
                //this.refreshFromServer();
            }
        }
    });

    Homepage.Views.Index = Backbone.View.extend({
        template: "homepage",
        el: '#mainContent',

        serialize: function() {
            return {
                collection: this.options.homepage
            };
        },

        initialize: function(){
            this.listenTo(this.options.homepage,{
                "reset": this.render,
                "fetch": function(){
                    $(this.el).html("Loading...");
                }
            });

        }
    });

    return Homepage;
});

如您所见,大型机"模板是加载到页面中的主要模板.我希望随后加载主页模板,该模板将填充到ID"#mainContent"中.不过,在这种情况下,#mainContent"尚不存在,因此主页模板不会加载到任何地方.

As you can see, the "main-frame" template is the main template that gets loaded into the page. I want the homepage template to load in afterwards, which gets populated into the id "#mainContent". In this case though, "#mainContent" doesn't exist yet so the homepage template isn't loaded in anywhere.

推荐答案

经过艰苦的努力,我决定离开主干模板,现在使用Backbone/RequireJS/localStorage适配器进行以下设置:

After much effort, I decided to move away from backbone-boilerplate, and now have the following setup using Backbone/RequireJS/localStorage adapter:

app.js:

define([
    'jquery',
    'underscore',
    'backbone',
    'router' // Request router.js
], function($, _, Backbone, Router){
    var initialize = function(){
        Router.initialize();
    };

    return {
        initialize: initialize
    };
});

main.js :

require.config({
    paths: {
        jquery: 'libs/jquery',
        underscore: 'libs/underscore',
        backbone: 'libs/backbone',
        'backbone.localStorage': 'libs/backbone.localStorage',
        templates: 'templates'
    },
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ['underscore','jquery'],
            exports: 'Backbone'
        },
        'backbone.localStorage': {
            deps: ['backbone'],
            exports: 'Backbone'
        }
    }
});

require([
    'app'

], function(App){
    App.initialize();
});

router.js :

define([
    'jquery',
    'underscore',
    'backbone',

    //Modules
    "modules/homepage"
],
    function ($, _, Backbone, Homepage) {
        "use strict";

        // Defining the application router, you can attach sub routers here.
        var Router = Backbone.Router.extend({
            routes:{
                "":"index"
            }
        });

        var initialize = function(){

            var app_router = new Router;

            app_router.on('route:index', function(){
                // Call render on the module we loaded in via the dependency array
                var collection = new Homepage.Collection();
                var homepage;
                collection.fetch({
                    success: function(){
                        if(collection.length === 0){
                            console.log('refreshing from server...');
                            collection.refreshFromServer({
                                success: function(data){
                                    collection.add(data);
                                    collection.invoke('save');
                                    homepage = new Homepage.Views.Index({
                                        collection: collection
                                    }).render();
                                }
                            })
                        }else{
                            console.log('already loaded in localStorage...');
                            homepage = new Homepage.Views.Index({
                                collection: collection
                            }).render();
                        }
                    }
                });

            });

            Backbone.history.start();
        };
        return {
            initialize: initialize
        };
    }
);

homepage.js:

define([
    "jquery",
    "underscore",
    "backbone",
    "backbone.localStorage",
    "text!templates/homepage.html"
],
function($, _, Backbone, localStorage, homepageTemplate){
    "use strict";

    var Homepage = { Views: {} };

    Homepage.Model = Backbone.Model.extend({

        defaults: function(){
            return {
                homepageData: {}
            };
        }
    });

    Homepage.Collection = Backbone.Collection.extend({
        localStorage: new Backbone.LocalStorage("RGPData"),

        refreshFromServer: function(options) {
            return Backbone.ajaxSync('read', this, options);
        },

        url: 'json/test.json',

        model: Homepage.Model
    });

    Homepage.Views.Index = Backbone.View.extend({
        template:"homepage",
        el: '#mainContent',

        initialize: function(){
            this.listenTo(this.collection, 'change', this.render);
            this.listenTo(this.collection, 'destroy', this.remove);
        },

        render: function(){
            console.log('rendering...');
            $(this.el).html( homepageTemplate, this.collection);
            return this;
        }
    });

    return Homepage;
});

以这种方式工作,我让应用程序使用localStorage适配器,而如果localStorage为空,则在我的集合中有一个"refreshFromServer"以从JSON文件读取.在将集合插入视图之前,先在路由器中获取该集合.

The way this works, I have the app use the localStorage adapter, while having a "refreshFromServer" in my collection to read from a JSON file if the localStorage is empty. The collection is fetched in the router, before inserted into the view.

我花了相当长的时间发现一切工作原理,因此希望这个答案可以帮助其他人比我做得更好.

This has been quite some time for me to discovery how everything works, so hopefully this answer will help anyone else out there get their footing a little bit better than I did.

一些注意事项,我使用text.js来引入模板.

A couple of notes, I use text.js in order to bring in the template.

另一个注意事项,我尝试添加了ribs.localStorage并仅返回"Backbone"(如

Another note, I tried including backbone.localStorage and returning as just 'Backbone' (as depicted in http://kilon.org/blog/2012/08/build-backbone-apps-using-requirejs/), but for some reason that didn't work and my homepage.js file kept saying "Backbone.Model is not defined". Therefore I ended up including both in the define.

这篇关于在加载主布局之前查看加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆