从ko.computed访问Html元素 [英] Access Html element from ko.computed
问题描述
可以从ko.computed函数访问bound元素吗?
Is it possible to access bound element from ko.computed function?
这个伪代码(简化为了清楚起见):
Something like this pseudo code (simplified for clarity):
<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';
});
仅显示第二个元素。
注意:我知道我可以为每个元素单独计算,但在我的情况下是不可能的。
Note: I'm aware I can have a separate computed for every element, but it is not possible in my case.
编辑:
好的 - 我会给出一个更准确的例子。以下与我所拥有的类似:
Ok - I'll give a more accurate example. The following is similar to what I have:
<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原则的丑陋违反,我想找到一种重构它的方法。上面的伪代码可以解决它,但是我是开放的建议...
This is an ugly violation of the DRY principle, and I would like to find a way to refactor it. The pseudo code above may solve it, but I'm open for suggestions...
推荐答案
你创建了一个简短的,简化的例子,通常很好。但是,您似乎已经引入了 XY问题。因此,这个答案可能或可能不是有帮助的。
You've created a short, simplified example, which is normally great. However, it feels like you've introduced an XY-problem instead. As such, this answer may or may not be helpful.
您正在尝试在您的中的视图视图模型。应该是相反的方式!这样做会更有意义:
You're trying to introduce a dependency on the View in your ViewModel. It should be the other way around! Something like this would make more sense:
<h1 data-bind="visible: myComputed, attr { id: myId }"></h1>
请注意使用 attr binding 设置id。您的ViewModel应该相应地构建:
Note the use of the attr binding to set the id. Your ViewModel should be constructed accordingly:
var activeHeaderId = 'id2';
var viewModel = function(id) {
var self = this;
self.myId = ko.observable(id);
self.myComputed = ko.computed(function() {
return self.myId() === activeHeaderId;
});
}
这篇关于从ko.computed访问Html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!