[英]Add mixin with ko.computed to knockout viewmodel
閱讀本文后: 重新學習javascript mixin,我想將一些常用的剔除計算函數移至mixin並將其混合到需要該功能的每個viewmodel中。
首先是mixin功能
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 })
};
然后調用將mixin混合到目標對象原型中
asActor.call(SenderActor.prototype);
asActor.call(ReceiverActor.prototype);
我的問題似乎是這個 (或在viewmodel內部設置為此的 self )指向Windows對象而不是viewmodel。 有任何想法嗎? Javascript mixins對我來說是新手,所以我可能在這里缺少明顯的東西。
asActor.call(SenderActor.prototype);
執行以下操作-
asActor
並將SenderActor.protototype
對象作為this
this.nrOfEmployees = ko.computed(...)
在SenderActor.protototype內部創建一個SenderActor.protototype
this
仍然指向SenderActor.protototype
取決於您的SenderActor.protototype
是否有employees
,或者它的原型鏈中,此代碼是否會產生錯誤。
現在, 我假設這種行為不是您要瞄准的對象。
嘗試運行asActor.call(this);
在SenderActor構造函數中。
當您通過函數創建新對象時,例如說new asActor(),將為您返回一個默認值-魔法“ this”。 僅在運行函數時必須添加return語句。
我已經測試了您的代碼,它沒有問題,但是從asActor運行沒有返回值。
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 })
return this;
};
正如奧爾加所說,在原型本身上創建計算機並不是我的初衷。 我選擇的解決方案是使用基類:
var Base = function () {
var extenders = [];
this.extend = function (extender) {
extenders.push(extender);
};
this.init = function () {
var self = this; // capture the class that inherits off of the 'Base' class
ko.utils.arrayForEach(extenders, function (extender) {
// call each extender with the correct context to ensure all
// inheriting classes have the same functionality added by the extender
extender.call(self);
});
};
};
在生成代碼中,我在所有viewmodel構造函數中添加了this.Init()調用 。
最后,我在每個視圖模型上調用了.extend函數,以將這些函數混合在一起:
SenderActor.prototype.extend(asActor);
ReceiverActor.prototype.extend(asActor);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.