After reading this article: A fresh look at javascript mixins I wanted to move some common knockout computed functions to a mixin and mix that into each viewmodel that needs the functionality.
First the mixin function
var asActor = function() {
this.nrOfEmployees = ko.computed(function () {
if (this.employees())
return this.employees().length;
return 0;
}, this).extend({ throttle: 20 });
this.nrOfAddresses = ko.computed(function () {
if (this.addresses())
return this.addresses().length;
return 0;
}, this).extend({ throttle: 20 })
};
Then the call to mix the mixin into the target objects prototype
asActor.call(SenderActor.prototype);
asActor.call(ReceiverActor.prototype);
My problem seems to be that this (or self which is set to this inside the viewmodel) points to the windows object and not the viewmodel. Any ideas? Javascript mixins is new to me so I'm probably missing something obvious here.