Monday, May 20, 2024
80
rated 0 times [  81] [ 1]  / answers: 1 / hits: 23682  / 12 Years ago, mon, february 18, 2013, 12:00:00

I have the code duplication problem in the next case. On my page I have a lot of blocks that I need to show / hide by clicking to link:



<div>
<a data-bind=click: showHiddenFirst, visible: isVisibleFirsthref=#>Show first</a>
<div data-bind=visible: !isVisibleFirst() style=display:none>
hidden content first
</div>
</div>
<div>
<a data-bind=click: showHiddenSecond, visible: isVisibleSecondhref=#>Show second</a>
<div data-bind=visible: !isVisibleSecond() style=display:none>
hidden content second
</div>
</div>


And my JS



var vm = function(){
this.isVisibleFirst = ko.observable(true);

this.showHiddenFirst = function(){
this.isVisibleFirst(false)
};

this.isVisibleSecond = ko.observable(true);

this.showHiddenSecond = function(){
this.isVisibleSecond(false)
};
};

ko.applyBindings(new vm());


Here is jsfiddle example http://jsfiddle.net/sstude/brCT9/2/



Question is how to avoid all this show / visible duplication? Maybe I need some custom binding where I put id of my hidden block or smth. else? Any patterns that you can suggest?


More From » design-patterns

 Answers
124

Here was a thought at encapsulating this functionality completely in an observable for your specific scenario:



ko.bindingHandlers.clickVisible = {
init: function(element) {
var visible = ko.observable(true),
opposite = ko.computed(function() { return !visible(); }),
clickHandler = visible.bind(null, false);

//apply bindings to anchor
ko.applyBindingsToNode(element, { click: clickHandler, visible: visible });

var sibling = element.nextSibling;
//find the div (as text nodes, etc. will show up in nextSibling)
while (sibling && sibling.nodeType != 1) {
sibling = sibling.nextSibling;
}

//apply bindings to div
if (sibling) {
ko.applyBindingsToNode(sibling, { visible: opposite });
}
}
};


It could be tweaked further, as necessary, if maybe the value passed into the binding should matter.



Example: http://jsfiddle.net/rniemeyer/gCgy5/


[#80160] Saturday, February 16, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;