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

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

问题描述

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

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

电子邮件列表是一个名为 电子邮件 的 Knockout 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 这是viewmodel中的一个方法:

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 ver 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天全站免登陆