我一直在创建一个htmlHelper函数,使用TypeScript和KnockoutJS编辑电子邮件列表。
电子邮件列表是一个名为“ObservableArray ”的淘汰赛( Knockout ),我有一个针对每一项的链接来删除它们。这是HTML片段:
<ul data-bind="foreach: emails" >
<li>
<a href="#" data-bind="click: $parent.deleteItem">Delete</a>
<span data-bind="text: $data"></span>
</li>
</ul>delete链接绑定到$parent.deleteItem,这是视图模型中的一个方法:
// remove item
public deleteItem(emailToDelete: string) {
// remove item from list
this.emails.remove(emailToDelete);
}在执行deleteItem方法之前,所有这些都可以工作。此方法中的" this“在调用时是数组中的项,而不是视图模型。因此,this.emails是一个空引用,并且失败。
我知道TypeScript支持Lambda语法,但是我找不到正确的方法来编写这个语法(很少有例子)。
还是我可以采取不同的方法?
发布于 2012-11-08 08:45:22
通过在类构造函数中声明方法主体,可以获得“this”的正确闭包。
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);
}
}
}更新:
似乎由于类型记录ver0.9.1,通过使用lambda字段初始化器,您可以获得相同的结果:
class VM {
public deleteItem = (emailToDelete: string) => {
this.emails.remove(emailToDelete);
}
}发布于 2013-05-23 15:57:31
戴手套的人!只需将$parent绑定如下:
<a href="#" data-bind="click: $parent.deleteItem.bind($parent)">Delete</a>发布于 2012-11-08 08:44:57
declare class Email { }
declare class ObservableArray {
remove(any): void;
}
class MyViewModel {
public emails : ObservableArray;
constructor() {
Rebind(this);
}
public deleteItem(emailToDelete: Email) {
this.emails.remove(emailToDelete);
}
}
function Rebind(obj : any)
{
var prototype = <Object>obj.constructor.prototype;
for (var name in prototype) {
if (!obj.hasOwnProperty(name)
&& typeof prototype[name] === "function") {
var method = <Function>prototype[name];
obj[name] = method.bind(obj);
}
}
}您可能需要一个用于Function.bind()的多填充
// Polyfill for Function.bind(). Slightly modified version of
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
if (typeof Function.prototype.bind !== "function") {
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = <any[]> Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP && oThis ? this: oThis, aArgs.concat());
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}https://stackoverflow.com/questions/13277537
复制相似问题