2013-05-08 57 views
2

如果我在jquery事件中,我不知道如何訪問類變量。下面的示例如何訪問jquery事件內部的類變量?

/// <reference path="../typings/jquery/jquery.d.ts" /> 

export class Notes { 

    // i want to access this inside of the click event 
    test = "test"; 

    foo() { 
     //works here 
     alert(this.test); 

     $("#testDiv").click(function() { 

      // context of this changes so this no longer works 
      alert(this.test); 

      //how do i access the test varible in here? 



     }) 
    } 
} 

回答

3

如果使用lambda表達式,它結合this到封閉範圍內的this

export class Notes { 
    private test: string = "test"; 

    foo() { 
     //works here 
     alert(this.test); 

     $("#testDiv").click(() => { 
      alert(this.test); 
     }) 
    } 
} 

被翻譯成

var Notes = (function() { 
    function Notes() { 
     this.test = "test"; 
    } 
    Notes.prototype.foo = function() { 
     var _this = this; 
     alert(this.test); 
     $("#testDiv").click(function() { 
      alert(_this.test); 
     }); 
    }; 
    return Notes; 
})(); 
exports.Notes = Notes; 

不過要小心,jQuery的回調裏面,你會不能夠訪問一個DOMElement如預期,因爲this翻譯。如果您希望能夠同時做到這兩點,請將this添加到閉合變量中:

export class Notes { 
    private test: string = "test"; 

    foo() { 
     alert(this.test); 
     var self = this; 
     $("#testDiv").click(function() { 
      alert(self.test); 
      $(this).hide(); // still works 
     }) 
    } 
} 
1

我找到了一種方法,但我覺得可能有更好的方法?

export class Notes { 
    test = "test"; 

    foo() { 
     var self = this; 

     $("#testDiv").click(function() { 
      alert(self.test); 
     }) 
    } 
}