1

我刚刚开始学习模块化设计原则,我相信我不了解我的一种方法的背景。在控制台中,我得到Uncaught TypeError: Cannot read property 'val' of undefined - line 19. 我正在使用 Firebase,如果这很重要的话。

这是我的代码:

(function(){
    var UpdateTable = {
        resources: Resources,
        init: function(){
            this.cacheDom();
            this.render();
            this.update(snapshot); // Changed this line ///
        },
        render: function(){
            this.resources.on('value', this.update);
        },
        cacheDom: function(){
            this.$table = $('#resourceTable');
        },
        update: function(snapshot){
            console.log(snapshot.val());
            for(var resource in this.resources){
                this.$table.append('<tr><td>' + this.resources[resource].name + '</td><td>' + this.resources[resource].language + '</td></tr>');
            }
        }
    };
    UpdateTable.init();
})();
4

2 回答 2

1

如果你想让这个真正模块化,我建议snapshot作为你的模块的参数传递。这将解决您的问题。

(function(snapshot){ // <----- Here I receive snapshot from the invoker
    var UpdateTable = {
        resources: Resources,
        init: function(){
            this.cacheDom();
            this.render();
            this.update(snapshot); // Changed this line ///
        },
        render: function(){
            this.resources.on('value', this.update);
        },
        cacheDom: function(){
            this.$table = $('#resourceTable');
        },
        update: function(snapshot){
            console.log(snapshot.val());
            for(var resource in this.resources){
                this.$table.append('<tr><td>' + this.resources[resource].name + '</td><td>' + this.resources[resource].language + '</td></tr>');
            }
        }
    };
    UpdateTable.init();
})(snapshot); // <---- Here I am passing snapshot from global context to the module context
于 2015-10-11T22:11:57.560 回答
0

您指定 update 应该接受一个参数 - shapshot - 但没有在 init() 中传递它。当你给一个函数一个参数时,它是一个隐式变量声明。

var args = 1;
function f(args) {
    console.log(args);
}

f();
// => 'undefined'

相反,你想要:

var args = 1;
function f() {
    console.log(args); // args now looks to the outer scope
}

f();
// => 1

或者

var args = 1;
function f(args) {
    console.log(args); 
}

f(args);  // args is explicitly passed in
// => 1
于 2015-10-11T21:58:23.217 回答