是否可以从 ko.computed 函数访问绑定(bind)元素?
类似于此伪代码(为清楚起见进行了简化):
<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 原则,我想找到一种方法来重构它。上面的伪代码可能会解决它,但我愿意接受建议...
最佳答案
您已经创建了一个简短的简化示例,这通常很棒。但是,感觉就像您引入了一个 XY-problem反而。因此,此答案可能有帮助,也可能没有帮助。
您正试图在您的 ViewModel 中引入对 View 的依赖。应该反过来吧!这样的事情会更有意义:
<h1 data-bind="visible: myComputed, attr { id: myId }"></h1>
注意 attr binding 的使用设置ID。您的 ViewModel 应该相应地构建:
var activeHeaderId = 'id2';
var viewModel = function(id) {
var self = this;
self.myId = ko.observable(id);
self.myComputed = ko.computed(function() {
return self.myId() === activeHeaderId;
});
}
关于javascript - 从 ko.computed 访问 Html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16296774/