0

アプリケーションにいくつかの小さなウィジェットがあり、作成/初期化時に一連のイベント ハンドラーをメイン コンテナー要素にアタッチします。

widget = function(){
    this.el = $("#someelement");
    this.init = function(){
        doAjax(function(data)){
            this.el.html(data)
            .on("click", function(){
                //attach some handler here
            })
            .on("change", ("div.class"), function(){
                //attach some handler here
            });
        } 
    }
    this.reload = function(){
        this.init();
    }
}

ここで私の問題は明らかです。ウィジェットをリロードするたびに (init 関数を呼び出して)、要素にハンドラーを再アタッチします。次に、ハンドラーをトリガーすると、「リフレッシュ」した回数だけハンドラーが実行されます。私は複数のことを試しました:

this.el.empty().html(data)
this.el.off("*").html(data)
this.el.html(data)
.off("click change")
this.el.children.remove().end().html(data)

などなど。私が実際にイベント ハンドラーを削除することはありません。私にできることは、それらを追加/追加することだけです。私はそれらをクリアすることはできません。私は何を間違っていますか?

4

1 に答える 1

1
widget = function(){
    this.el = $("#someelement");
    this.isInitialLoad = false;

    this.init = function(){
        doAjax(function(data)){
            if(!isInitialLoad){
                this.el.html(data)
                .on("click", function(){
                    //attach some handler here
                })
                .on("change", ("div.class"), function(){
                    //attach some handler here
                });
            }
            else {
                this.el.html(data);
            }
        } 
    }
    this.reload = function(){
        this.init();
    }
}

または、懸念事項を分離します。

widget = function(){
    this.el = $("#someelement");

    this.init = function(){
        doAjax(function(data) {
            this.el.html(data)
            .on("click", function(){
                //attach some handler here
            })
            .on("change", ("div.class"), function(){
                //attach some handler here
            });
        });
    }
    this.reload = function(){
        doAjax(function(data) { this.el.html(data); });
    }
}
于 2013-03-28T20:20:26.197 に答える