骨干console.log返回集合且未定义 [英] Backbone console.log returning collection and undefined

查看:87
本文介绍了骨干console.log返回集合且未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Backbone项目发生了一些奇怪的事情.我正在将其重建为AMD,并且必须更改一些变量名称才能使其再次运行.我有一个要传递给视图的集合,但是当我console.log集合时,我同时得到了对象和null.

Something odd is going on with my Backbone project. I'm rebuilding it as AMD and I'm having to change some variable names to get it working again. I have a collection I'm passing into a view, but when I console.log the collection, I get both the object and null.

这是我的观点:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/tablesCollection',
    'views/tablesView',
    'views/tableView'
],
function($, _, Backbone, tableModel, tablesCollection, tableView) {
    var tv = Backbone.View.extend({
        tagName: 'div',
        initialize: function() {
            console.log(this.collection);
            this.collection.on('reset', this.render, this);
            this.template = this.options.template;
            this.url = this.collection.url;

        },
        render: function() {
            //tablesCollection.collection.each(this.addOne, this);
            return this;
        },
        addOne: function(model) {
            var t = new tableView({ model: model, template: this.template, url: this.url });
            this.$el.append(t.render().el);
            return this;
        },
        stripQueryString: function(url) {
            return url.split('?')[0];
        }
    });

    return tv;
});

您将在项目中看到console.log几行.结果就是我在Firebug中得到的东西:

You'll see the console.log several lines down in the project. Here is what I get in Firebug as a result:

两者都引用相同的行号.这是对象中的内容:

Both cite the same line number. Here is what's in the object:

这是怎么回事?为什么同一件事我得到两个结果?其中之一是我想要的,而另一个不是.

What is going on here? Why am I getting two results for the same thing? One of them is what I want and the other one isn't.

这是我实例化视图的地方:

Here is where I instantiate the view:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/TablesCollection',
    'views/tablesView',
    'views/tableView'
], function($, _, Backbone, TableModel, tablesCollection, tablesView, tableView) {
    var t = new tablesCollection(null, { url: 'main-contact'} );
    var tables = new tablesView({ collection: t, template: 'main-contact-template'});
    $('#web-leads').html(tables.render().el);

});

这是我的收藏集:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel'
],
function($, _, Backbone, tableModel) {
    var tablesCollection = Backbone.Collection.extend({
        url: this.url,
        model: tableModel,
        initialize: function(models, options) {
            if (options && options.url) {
                this.url = options.url;
            }
            this.fetch({
                success: function(data, options) {

                }
            });
        }
    });

    return tablesCollection;
});

另外两个文件:

// Filename: app.js
define([
    'jquery',
    'underscore',
    'backbone',
    'router' // Request router.js
], function($, _, Backbone, Router){
    var initialize = function(){
    // Pass in our Router module and call it's initialize function
    Router.initialize();
};

return {
    //initialize: initialize  <--This is where the second init call was happening.
};
});

Main.js:

 require.config({
        paths: {
            //jquery: 'libs/jquery/jquery-1.8.3.min',
            underscore: 'libs/underscore/underscore-min',
            backbone: 'libs/backbone/backbone-min'
        }
    });

    if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
      define( 'jquery', [], function () { return jQuery; } );
    }

    //the "main" function to bootstrap your code
    require(['jquery', 'underscore', 'backbone', 'app'],
        function () {
            var App = require('app');
            App.initialize();
            // console.log($);
            // console.log(_);
            // console.log(Backbone);
    });

推荐答案

您的先前版本代码比此经过编辑的版本更有意义,因为在先前版本中,您实际上要推送到console.log遇到麻烦的对象

You prior version of the code made more sense than this edited version, as in the prior version you were actually pushing to console.log the object that was giving trouble

// contents of 'that/view/that/gives/me/problems.js'
define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/tablesCollection',
    'views/tablesView',
    'views/tableView'
],
function($, _, Backbone, tableModel, tablesCollection, tableView) {
    console.log("factory", tablesCollection.collection); // <- you did not have this line. my addition
    var tv = Backbone.View.extend({
        tagName: 'div',
        initialize: function() {
            console.log("init", tablesCollection.collection); // <- your prior version. Point of your error
            this.collection.on('reset', this.render, this);
            this.template = this.options.template;
            this.url = this.collection.url;

        }
        // ...
    });

    return tv;
});

现在让它显示两次的原因是,您在上方定义的视图在某处初始化了两次.

Now the reason you have it show up twice is because the view you define above is initialized twice somewhere.

首次初始化时,将显示您所看到的值.指针tablesCollection周围的第二次被某事清除,因此,您会遇到该错误.

First time it's initialized it shows the value as you can see. The second time around the pointer tablesCollection is cleaned up by something and, hence, you have that error.

现在清除tablesCollection的内容以及为什么在您显示的代码中我看不到任何地方.这可能与在代码中的某个地方重新请求"collections/tablesCollection"模块有关.从您的"collections/tablesCollection"模块代码中可以看到,您在每个工厂调用中重新定义了输出.我要做的是计算一次并投放缓存:

Now what cleans up tablesCollection and why I don't see anywhere in the code you present. It has likely something to do with re-requiring 'collections/tablesCollection' module somewhere in your code. As I can see from your 'collections/tablesCollection' module code, you REDEFINE the output on every factory call. What I would do is calc it once and serve cached:

// contents of 'collections/tablesCollection.js'
;(function(){

    var mythings = {}

    function initializer($, _, Backbone, tableModel){
        return Backbone.Collection.extend({
            url: 'url',
            model: tableModel,
            initialize: function(models, options) {
                // ...
            }
        });
    }

    define([
        'jquery',
        'underscore',
        'backbone',
        'models/tableModel'
    ],
    function($, _, Backbone, tableModel) {
        if (!mythings.tablesCollection){
            // this will be done on first run.
            mythings.tablesCollection = initializer($, _, Backbone, tableModel)
        }
        // all others will just return same exact instance of collection class
        return mythings.tablesCollection
    })

})();

向AMD规格组询问是否有机会根据需要重新运行工厂"功能.即时答案是不太可能",而长期答案是可能(如果使用不同的名称询问)"

Asked the AMD spec group if there is a chance of 'factory' function rerunning on every require. Immediate answer was "Not likely" but long term answer is "Possible (if asked under different name)"

我在上面的代码段中添加了注释行,以指示它们是什么文件.

I added comment lines to the code snippet above indicating what files they are.

我还在第一个代码段中添加了console.log行,该行应有助于您了解问题不在于AMD loader.您只需在某处两次初始化视图即可.

I also added a console.log line in the first snippet that should help you understand that the issue you have is NOT with AMD loader. You simply initialize the view twice somewhere.

运行带有注释行的代码(如顶部代码片段)时,您会看到factory日志行仅出现一次,而init行却出现两次,就像您的origianl错误屏幕截图一样.

When you run the code with comment lines like in the top snippet you will see factory log line shoing up only once and init line twice, like in your origianl error screenshot.

您需要跟踪使用该tv变量中返回的视图的位置.您将其初始化两次.

You need to trace where you use the view returned in that tv variable. You are initing it twice.

关于第二次运行中对tablesCollection的引用(清除)发生了什么,我不知道,也看不到您提供的摘录中的任何地方.

As to what happens to (what clears) reference to tablesCollection in the second run I don't know and don't see anywhere in the snippets you provided.

这篇关于骨干console.log返回集合且未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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