TypeScript和Knockout绑定到“此"问题-需要lambda函数吗? [英] TypeScript and Knockout binding to 'this' issue - lambda function needed?

查看:92
本文介绍了TypeScript和Knockout绑定到“此"问题-需要lambda函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用TypeScript和KnockoutJS创建htmlHelper函数来编辑电子邮件列表.

I've been creating a htmlHelper function using TypeScript and KnockoutJS to edit a list of emails.

电子邮件列表是一个称为电子邮件的淘汰赛ObservableArray,我有一个链接指向每个项目以将其删除.这是HTML片段:

The list of emails is a Knockout ObservableArray called emails, and I have a link against each item to delete them. This is the HTML fragment:

<ul data-bind="foreach: emails" >
    <li>
        <a href="#" data-bind="click: $parent.deleteItem">Delete</a>
        &nbsp;<span data-bind="text: $data"></span>
    </li>
</ul>

删除链接绑定到 $ parent.deleteItem ,这是视图模型中的一种方法:

The delete link is bound to $parent.deleteItem this is a method in the viewmodel:

// remove item
public deleteItem(emailToDelete: string) {
    // remove item from list
    this.emails.remove(emailToDelete);
}

这一切一直有效,直到执行deleteItem方法为止.调用此方法时,此方法中的"this"是数组中的项目,而不是视图模型.因此,this.emails是空引用,并且失败.

This all works until the deleteItem method is executed. The "this" in this method when it is called is the item in the array, and not the view model. Hence this.emails is a null reference and fails.

我知道TypeScript支持Lambda语法,但是我找不到正确的编写方式(那里没有几个示例).

I know that TypeScript supports the Lambda syntax but I can't find the right way to write this (there few examples out there).

或者我可以采取其他方法吗?

Or is there a different approach I could take?

推荐答案

通过在类构造函数中声明方法主体,可以正确关闭'this'

You can get correct closure for 'this' by declaring method body inside class constructor

class VM {
    public deleteItem: (emailToDelete: string) => void;

    constructor() {
        this.deleteItem = (emailToDelete: string) => {
            // 'this' will be pointing to 'this' from constructor
            // no matter from where this method will be called
            this.emails.remove(emailToDelete);
        }
    }        
}

更新:

似乎从Typescript版本0.9.1开始,您可以通过使用lambda字段初始化程序来获得相同的结果:

It seems that since Typescript ver 0.9.1 you can achieve the same result by using lambda field initializers:

class VM {
    public deleteItem = (emailToDelete: string) => {
        this.emails.remove(emailToDelete);
    }        
}

这篇关于TypeScript和Knockout绑定到“此"问题-需要lambda函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆