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

If you want to make this truly modular, I suggest to pass snapshot as a parameter for your module. This will fix your issue.

(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 に答える