Knockout: how to switch the visibility of multiple divs to a button?

I want to switch the visibility of multiple divs using knockout. The following is a rough idea of ​​my problem -

<button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <div> Div 1 </div> <div> Div 2 </div> <div> Div 3 </div> 

By default, "Div 1" should be visible.

When I click individual buttons, it should only display related divs based on the buttons pressed.

I looked through the examples of β€œKnockout”, but I don’t understand how to do this effectively.

Please, help!

+6
source share
1 answer

The following will do the job for you. This is not ideal, but should give you a platform for work.

First, everything in Knockout is tied to a view model. You want to be able to control the visibility of the 3 sections, so here is a presentation model that might work. As I said, not perfect :)

 var buttonVm = new function(){ var self = this; // Flags for visibility // Set first to true to cover your "first should be open" req self.button1Visible = ko.observable(true); self.button2Visible = ko.observable(false); self.button3Visible = ko.observable(false); self.toggle1 = function(){ self.button1Visible(!self.button1Visible()); } self.toggle2 = function(){ self.button2Visible(!self.button2Visible()); } self.toggle3 = function(){ self.button3Visible(!self.button3Visible()); } } 

You will need to change the markup to: -

 <!-- events here. When clicked call the referenced function --> <button type="button" data-bind="click: toggle1">Button 1</button> <button type="button" data-bind="click: toggle2">Button 2</button> <button type="button" data-bind="click: toggle3">Button 3</button> <!-- Visibility set here --> <div data-bind="visible: button1Visible"> Div 1 </div> <div data-bind="visible: button2Visible"> Div 2 </div> <div data-bind="visible: button3Visible"> Div 3 </div> 

A few things to note here. First, I added a type attribute. Without it, the default button behavior will be to try to submit your form.

The plot of all: -

 // Create view model var vm = new buttonVm(); ko.applyBindings(vm); 
+17
source

Source: https://habr.com/ru/post/920893/


All Articles