【问题标题】:Backbone boilerplate: "this.model is undefined"骨干样板:“this.model 未定义”
【发布时间】:2013-02-11 19:39:04
【问题描述】:

我是一个骨干新手,所以我在设置应用程序时有点摸索。我正在使用主干样板(https://github.com/tbranyen/backbone-boilerplate)和 github-viewer(https://github.com/tbranyen/github-viewer)作为参考,尽管在运行时我似乎得到了“this.model is undefined”。

这是我当前的 router.js:

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();
                this.homepage.fetch();
            },

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

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

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

        });

        return Router;
    }
);

还有我的 homepage.js 模块:

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

    var Homepage = app.module();

    Homepage.Model = Backbone.Model.extend({
        defaults: function(){
            return {
                homepage: {}
            };
        }
    });

    Homepage.Collection = Backbone.Collection.extend({
        model: Homepage.Model,

        cache: true,

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

        initialize: function(models, options){
            if (options) {
                this.homepage = options.homepage;
            }
        }
    });

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

        render: function(){
            var tmpl = _.template(this.template);

            $(this.el).html(tmpl(this.model.toJSON()));

            return this;
        },

        initialize: function(){
            this.listenTo(this.options.homepage, {
                "reset": function(){
                    this.render();
                },

                "fetch": function() {
                    $(this.el).html("Loading...");
                }
            });
        }
    });

    return Homepage;
});

提前感谢您的帮助!

更新:经过大量谷歌搜索(你应该看到我打开了多少标签),我认为我取得了一点进展,但仍然没有运气。我更新了我的路由器以具有以下内容:

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

我对 homepage.js 模块进行了一些修改,现在看起来像这样:

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',

        initialize: function(){
            var self = this;
            this.collection = new Homepage.Collection();
            this.collection.fetch().done( function(){
                self.render();
            });
        },

        render: function(){
            var data = this.collection;

            if (typeof(data) === "undefined") {
                $(this.el).html("Loading...");
            } else {
                $(this.el).html(_.template(this.template, data.toJSON()));
            }
            return this;
        }
    });

    return Homepage;
});

如您所见,我有 localStorage 代码,但现在注释掉了,因为我只想让一切都先运行。最终目标是进行初始调用,从 JSON 文件加载数据,然后使用 localStorage 继续。在用户与我的应用进行多次交互后,该应用稍后会提交数据。

我正在加载主视图,尽管主页模块没有填充主视图中的#mainContent 容器。

我做了所有我能做的谷歌搜索,但沮丧的是它并没有让我陷入困境。再次感谢您查看此内容,感谢您提供任何反馈!

【问题讨论】:

    标签: backbone.js requirejs


    【解决方案1】:

    我认为您的类层次结构在这里有点不稳定。例如,您的 Homepage.Collection 实例实际上是从选项中分配了 homepage 属性。然后将Homepage.Collection 的实例作为homepage 选项传递给Homepage.Views.Index... 这有点难以理解。

    也就是说,在我看来,您的问题只是在构造 Homepage.Views.Index 时没有提供 model 选项:

    new Homepage.Views.Index(collections)
    

    collections 没有model 属性,因此我看不到稍后在视图中this.model.toJSON() 如何可以访问模型。基本上,您似乎希望Homepage.Views.Index 处理模型的集合,而不仅仅是一个。因此,您可能需要在您的 render 函数中使用一个循环来覆盖 this.collection(并且您应该将视图的构造更改为具有 collection 选项而不是 homepage 选项)。

    如果我在这里遗漏了什么或者我不清楚,那是因为我之前提到的这种数据模型的古怪。随意澄清你是如何推理出来的,我们可以再试一次:)

    【讨论】:

    • 哦,谢谢你看这个!我还有一大堆整理工作要做,最初的模型集合在示例代码中,我将其精简为一个集合。也就是说,它直到无法正常工作,将尽快尝试包含一些代码...
    • 再次感谢您的帮助。我最终解决了一堆问题,所以我发布了一个后续问题:stackoverflow.com/questions/14857166/…
    【解决方案2】:

    你的这个示例代码让我有点困惑,但我认为问题在于以下两行代码:

    ".homepage": new Homepage.Views.Index(collections)
    $(this.el).html(tmpl(this.model.toJSON()));
    

    看起来您将集合传递给视图,但在视图中您使用 this.model,因此错误“this.model is undefined”,因为它确实是未定义的。

    如果您不着急,我建议您重新开始。看来您尝试得太快了。我看到你有主干、requirejs(或其他一些模块加载器)和样板,对于刚接触主干的人来说,这是很多东西。相信我,我知道,因为我也相对较新。也许从一些你好世界的东西开始,然后慢慢地向上走。否则,通过各种项目的代码来破解你的方式可能会令人困惑。

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 2014-10-12
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多