I know the title may make it sound like this should just take a quick Google search to find the answer... but please see my code example below and you will find it's a little trickier than you may have first thought.
I am moving from KnockoutJS to Aurelia with ES6. It's my first time with both Aurelia and ES6... Anyway, the problem I am having is with the this
keyword and context. In KnockoutJS, I would just alias it like so at the top of the view model: var self = this;
. This does not seem to be possible in ES6 and I am told we should do something like: () => { this.foo ... }
. I've also found the following useful info:
https://www.sitepoint.com/bind-javascripts-this-keyword-react/
However, I can't seem to figure out how to apply any of those solutions in my case, so I am hoping someone can give me a hand here...
I have a view model as follows (most of the "fluff" has been cut out, to focus on the important parts):
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
});
}
}
How can I reference the main context this
from inside the detailInit
function?