1
function DialogWindow(contents, clickEvent){
// given a contents we can create a DialogWindow of that content
this.contents = contents;
this.domElement = $(".hideMe");

this.test = function(){
    console.log(this.contents);
}

$("div").click(this.test); //<-note this spot

/*
This function simply returns the html representation of the contents
This function should be called withen WindowPage so that it can fully figure out what
Arguments:
    container: the container that containes the WindowPage that this is apart of
    lanes: the number of lanes on the page. Defined as: lanes = (number of columns in WindowPage) * 3 + 1
*/
this.toHtml = function(container, lanes){

    var dialogWidth = container.width()/(lanes/2);
    var dialogSep = container.width()/lanes;

    var htmlWindow = jQuery('<div/>', {
        id: "dialogWindow"
    }).css("width", dialogWidth).css("height", dialogWidth).css("position","absolute");

    jQuery(this.contents.toHtml()).appendTo(htmlWindow);

    this.domElement = htmlWindow;

    return htmlWindow;
}

}

私の目標は、htmlWindow をクリックして DialogWindow の機能を実行することです。ただし、これを行うたびに、すべての DialogWindows プロパティが未定義を返します。行を置き換えると:

$("div").click(this.test);

$("div").click(this.test());

次に、関数 test() がすぐに実行され、機能します (つまり、this.contents がコンソールに表示されます)。ただし、その行をそのままにしておくと (つまり、クリックして test() 関数が起動するのを待つ)、未定義がコンソールに出力されます。

4

1 に答える 1

0

this内部はtestDialogWindow オブジェクトを指しておらず、クリックした dom 要素を指しているためです

1 つの解決策は、 $.proxy()を使用してカスタム実行プロキシをイベント コールバックに渡すことです。

this.test = function(){
    console.log(this.contents);
}
$("div").click($.proxy(this.test, this)); //<-note this spot

別の一般的な解決策は、クロージャー変数を使用することです

var self = this
this.test = function(){
    console.log(self.contents);
}
$("div").click(this.test); //<-note this spot

このシナリオでは、前者の方法を使用することをお勧めします

于 2013-08-30T02:30:19.130 に答える