我对使用ES6类的绑定上下文有问题。
下面是一个需要解释的小提琴。
当我在类上声明一个单击函数时,如下所示
class viewModel {
constructor() {
this.data = ko.observableArray([{ firstName: "phil" }, { firstName: "person" }]);
this.selectedPerson = ko.observable("none selected");
}
selectUser(data){
console.log(this);
this.selectedPerson(data.firstName);
}
}我必须在标记中提供如下所示的绑定:<div data-bind="text: firstName, click: $parent.selectUser.bind($parent)">
但是,当我在构造函数中声明单击时,我不必提供上下文。
有人知道为什么吗?
发布于 2017-01-20 11:42:35
“敲除”的事件绑定( click在幕后使用)做了三件事:
$data,apply绑定到当前$data的事件侦听器(来源)
这意味着当您点击用户时,会发生这样的情况:
viewModelInstance.selectUser.apply(user, [user, event]);如果您想在处理程序中引用this,那么了解箭头函数、原型方法和“未绑定”属性函数之间的区别是很重要的:
this.doSomething = function () { /* ... */ };
this.doSomething = () => { /* ... */ };
MyClass.prototype.doSomething = function() { /* ... */ };当你写:
this.selectUser = (data) => { /* ... */ };你实际上是这样做的:
this.selectUser = function(data) { /* ... */ }.bind(this);这意味着viewModel实例是方法的“固定”/bound。在构造函数之外定义它使其成为一个原型方法,可以通过其他代码绑定到任何this上下文。
搜索"es6箭头函数“和this,以找到更多关于如何工作的答案。例如:何时在ECMAScript 6中使用Arrow函数?
https://stackoverflow.com/questions/41761682
复制相似问题