查看下面第二个JS对象中的switch语句。
如何引用应该是它的第一个对象?
$parent.Sorttest()
似乎无法发挥作用。
function FListGroup(title, fListCount, fItemGroup) {
var self = this;
self.Title = title;
self.FListCount = fListCount;
self.FItemGroup = ko.observableArray(fItemGroup);
self.Sorttest = ko.observable("Score");
}
function FItemGroup(name, fItemSum, fItemCount, fItemAvrg) {
var self = this;
self.Name = name;
self.FItemSum = fItemSum;
self.FItemCount = fItemCount;
self.FItemAvrg = fItemAvrg;
self.DisplayedSort = ko.computed(function () {
switch($parent.Sorttest()) {
case "Score":
return FItemSum
break;
case "Count":
return FItemCount
break;
case "Average":
return FItemAvrg
break;
}
});
}
答案 0 :(得分:0)
我希望这不是Knockoutjs特有的,但你可以将实例传递给第二个?像这样:
function FListGroup() {
this.foo = function() {
console.log('foo() was called!');
};
}
function FItemGroup(FListGroupInstance) {
FListGroupInstance.foo();
}
var FListGroupInstance = new FListGroup();
FItemGroup(FListGroupInstance);
在您的情况下,您可以检查实例是否已存在,如下所示:
function FItemGroup(name, fItemSum, fItemCount, fItemAvrg) {
var self = this;
self.instance = false;
self.DisplayedSort = ko.computed(function () {
if (self.instance === false) {
self.instance = new FListGroup();
}
switch(self.instance.Sorttest()) {
case "Score":
return FItemSum
break;
case "Count":
return FItemCount
break;
case "Average":
return FItemAvrg
break;
}
});
}