Take the 2-minute tour ×

I did my first knockout.js application http://jsfiddle.net/Pqs7e/

For display application parts (books section, about section) I use jquery $("#id").show(). I feel this is not right way. How can I do this through the mechanism of the viewmodel?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

I would do it with special state observable which would identify which div to show:

function ViewModel(){
    var self = this;
    self.state = ko.observable();

Then you just bind it like this:

<div id="books" data-bind="visible: state() === 'books'>...</div>
<div id="about" data-bind="visible: state() === 'about'>...</div>

and switch between states like this:

this.get('#books', function() {

this.get('#about', function() {
share|improve this answer
Thank you very much –  Alexey Lisikhin Feb 12 '12 at 4:43
add comment

An alternate way to do this is with templates:

<div data-bind="template: state">
    Template renders here

Then your sections can be defined somewhere like this (in the same file or elsewhere):

<script id="books" type="text/html">
   Your markup here...

<script id="about" type="text/html">
   Your markup here...
share|improve this answer
add comment

Your Answer


