Pregunta

The Problem

I am picking up Typescript and just learned that lambda functions are used to (edit) set the value of this. However, I'm not sure how to pass my view model's this into a function that calls another method that I have not defined. In my case, I'm trying to call a Knockout method. See example:

Desired JavaScript:

var MyViewModel = (function () {
    function MyViewModel() {
        var _this = this;
        ...
        this.someMethod = function () {
            ko.utils.arrayForEach(this.array1(), function (item) {
                while (item.array2().length < _this.array3.length) {
                    item.array2.push(12345);
                }
            });
        };
  ...

Actual JavaScript:

var MyViewModel = (function () {
    function MyViewModel() {
        var _this = this;
        ...
        this.someMethod = function () {
            ko.utils.arrayForEach(_this.array1(), function (item) {
                while (item.array2().length < this.array3.length) {
                    item.array2.push(12345);
                }
            });
        };
  ...    

TypeScript:

method = () => {
    ko.utils.arrayForEach(this.array1(), function(item){
        while(item.array2().length < this.array3().length){
            item.array2.push(0);
        }
    })
 }

One Solution...

One solution I've used was to manually set this.array3().length to _this.array3.length(), but that's pretty hacky and I do not like it.

How should I go about passing the right this into my inner function?

¿Fue útil?

Solución

You need to use another lambda to continue the chain of this :

method = () => {
    ko.utils.arrayForEach(this.array1(), (item) => {  // NOTE here
        while(item.array2().length < this.array3().length){
            item.array2.push(0);
        }
    })
 }

Tips on this in TypeScript : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top