我正在学习Haxe和KnockoutJS,但是这个简单的代码不起作用(你可以在JSBin中查看)。我无法删除页面中的成员。
的index.html
<table>
<thead><tr>
<th>name</th><th></th>
</tr></thead>
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name" /></td>
<td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
</tr>
</tbody>
</table>
Main.hx
package ;
import js.Lib;
import knockout.*;
class Main {
static function main() {
Knockout.applyBindings(new MemberViewModel());
}
}
class MemberViewModel {
public var seats : Dynamic;
public function new() {
this.seats = Knockout.observableArray([
{name: "Steve"},
{name: "Bert"}
]);
}
public function removeSeat(seat) : Void {
trace(this.seats);
this.seats.remove(seat);
}
}
我无法理解this.seats
成为undefined
的原因。谢谢你的帮助。
答案 0 :(得分:2)
您正在丢失上下文,使用 bind 将上下文设为类
<a href="#" data-bind="click: $root.removeSeat.bind($root)">Remove</a>
<强> JSBin 强>
当方法作为参数传递或设置为变量然后调用时,您将丢失上下文。这个例子将显示我的意思更好
function someObject(){}
someObject.prototype.someMethod = function(){
console.log("Context: ",this);
}
var newObj = new someObject();
newObj.someMethod();
//Console will show: Context: someObject {someMethod: function}
var methodVar = newObj.someMethod;
methodVar();
//Console will show: Context: Window {...}
function fnCall(method){
method();
}
fnCall(newObj.someMethod);
//Console will show: Context: Window {...}
使用bind可以设置上下文
fnCall(newObj.someMethod.bind(newObj));
//Console will show: Context: someObject {someMethod: function}