I'm currently working through the tutorial on learn.knockoutjs.com and I've reached step 4 of the custom bindings tutorial. In the provided JavaScript code snippet, we have:
update: function(element, valueAccessor) {
// Give the first x stars the "chosen" class, where x <= rating
var observable = valueAccessor();
$("span", element).each(function(index) {
$(this).toggleClass("chosen", index < observable());
});
}
I've converted this to TypeScript as follows:
update: (element, valueAccessor) => {
var observable = valueAccessor();
$("span", element).each(index => {
$(this).toggleClass('chosen', index < observable())
});
}
This results in creating a _this variable to maintain the scope of the "update" function instead of the inner "span" function.
update: function (element, valueAccessor) {
var _this = this;
var observable = valueAccessor();
$("span", element).each(function (index) {
$(_this).toggleClass('chosen', index < observable());
});
}
The issue arises with $(_this)
. How can I ensure TypeScript provides me with the correct $(this)
?