typescript - How to access class variable inside of jquery event? -
if i'm inside jquery event, i'm not sure how can access class variables. example below
/// <reference path="../typings/jquery/jquery.d.ts" /> export class notes { // want access inside of click event test = "test"; foo() { //works here alert(this.test); $("#testdiv").click(function () { // context of changes no longer works alert(this.test); //how access test varible in here? }) } }
if use lambda expression, binds this
enclosing scope's this
.
export class notes { private test: string = "test"; foo() { //works here alert(this.test); $("#testdiv").click(() => { alert(this.test); }) } }
is translated into
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;
be careful however, inside jquery callback not able access domelement expected, since this
translated. if want able both, add this
variable in closure yourself:
export class notes { private test: string = "test"; foo() { alert(this.test); var self = this; $("#testdiv").click(function() { alert(self.test); $(this).hide(); // still works }) } }
Comments
Post a Comment