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

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -