The second argument to a computed observable (and manual subscription) allows you to bind the handler to a specific context, so you can have a reliable value of "this" when executing the function.
So, in my example it looks like:
var ViewModel = function() {
this.choices = ko.observableArray([
{ id: "1", name: "apple"},
{ id: "2", name: "orange"},
{ id: "3", name: "banana"}
]);
this.selectedId = ko.observable();
this.selectedObject = ko.computed(function() {
var id = this.selectedId();
return ko.utils.arrayFirst(this.choices(), function(choice) {
return id === choice.id;
});
}, this);
};
One common alternative is to cache the appropriate value of "this" in a variable and then reference it directly in the handler (variable is available based on how closures work in JS). In this case, it is not necessary to pass the second argument, as "this" is not a concern. So, it would look like:
var ViewModel = function() {
var self = this;
this.choices = ko.observableArray([
{ id: "1", name: "apple"},
{ id: "2", name: "orange"},
{ id: "3", name: "banana"}
]);
this.selectedId = ko.observable();
this.selectedObject = ko.computed(function() {
var id = this.selectedId();
return ko.utils.arrayFirst(self.choices(), function(choice) {
return id === choice.id;
});
});
};
You could certainly certainly say "self.items', "self.selectedId", etc. in the constructor, but the only place where "this" is a concern is when executing the handler. In this case, using "self.choices()" in the handler makes it so we don't need to use "this" at all.
Hope that makes sense.