是否可以从 ko.computed 函数访问绑定元素?
像这样的伪代码(为清楚起见进行了简化):
<h1 id="id1" data-bind="visible: myComputed">
<h1 id="id2" data-bind="visible: myComputed">
<h1 id="id3" data-bind="visible: myComputed">
...
self.myComputed = ko.computed(function(){
return <BOUND_ELEMNT>.id == 'id2';
});
导致仅显示第二个元素。
注意:我知道我可以为每个元素单独计算,但在我的情况下这是不可能的。
编辑:
好的 - 我会举一个更准确的例子。以下与我所拥有的类似:
<section id="id1" data-bind="visible: myComputed1">A lot of code</section>
<section id="id2" data-bind="visible: myComputed2">different lots of code</section>
<section id="id3" data-bind="visible: myComputed3">Other lots of code</section>
...
// This field's value changes over time (between 'id1', 'id2' and 'id3').
// Some complex logic changes this field,
// and as a result only one h1 is showing at a time.
self.myField = ko.observable();
self.myComputed1 = ko.computed(function(){
return self.myField() == 'id1';
});
self.myComputed2 = ko.computed(function(){
return self.myField() == 'id2';
});
self.myComputed3 = ko.computed(function(){
return self.myField() == 'id3';
});
这是对 DRY 原则的严重违反,我想找到一种方法来重构它。上面的伪代码可能会解决它,但我愿意接受建议......