我知道标题可能听起来像是应该快速谷歌搜索找到答案...但请看下面我的代码示例,你会发现它比你原先想象的要复杂一点。 / p>
我正在从 KnockoutJS 转移到 Aurelia ES6 。这是我第一次使用 Aurelia 和 ES6 ...无论如何,我遇到的问题是使用this
关键字和上下文。在 KnockoutJS 中,我只是在视图模型的顶部对其进行别名:var self = this;
。在 ES6 中似乎无法做到这一点,我被告知应该执行以下操作:() => { this.foo ... }
。我还发现了以下有用信息:
https://www.sitepoint.com/bind-javascripts-this-keyword-react/
但是,我似乎无法弄清楚如何在我的案例中应用任何这些解决方案,所以我希望有人可以帮我一把......
我有一个视图模型如下(大部分“绒毛”已被剪掉,重点关注重要部分):
export class MenuItemViewModel {
constructor(parent) {
this.parent = parent;
}
init() {
let self = this;
$("#items-grid").kendoGrid({
data: null,
dataSource: {
//etc
pageSize: this.parent.gridPageSize,
//etc
},
dataBound: function (e) {
let body = $('#items-grid').find('tbody')[0];
if (body) {
self.parent.templatingEngine.enhance({ element: body, bindingContext: self.parent });
}
},
//etc
detailTemplate: kendo.template($("#items-template").html()),
detailInit: this.detailInit
});
}
detailInit(e) {
// I can't even alias "this" here, because the context is not what I expected.
// I tested by doing a `console.log(this.someProperty)` which should have worked, but didn't
let self = this;
var detailRow = e.detailRow;
detailRow.find(".tabstrip").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find(".detail-grid").kendoGrid({
data: null,
dataSource: {
//etc
pageSize: this.parent.gridPageSize, // Error message when breaking here... "this.parent is undefined"
//etc
},
dataBound: function (e) {
let body = this.element.find("tbody")[0];
//let body = $('#grid').find('tbody')[0];
if (body) {
self.parent.templatingEngine.enhance({ element: body, bindingContext: self.parent });
}
},
//etc
detailTemplate: kendo.template($("#items-template").html()),
detailInit: this.detailInit
});
}
}
如何从this
函数中引用主要上下文detailInit
?