Knockout.js URL Routing

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

For parts of the application to view (section "Books" section) I use jquery $ ("# id"). show (). I feel this is the wrong way. How can I do this using the viewmodel mechanism?

+4
source share
2 answers

I would do this with a special observable state that 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 as follows:

 this.get('#books', function() { self.state("books"); }); this.get('#about', function() { self.state("about"); }); 
+4
source

An alternative way to do this is with templates:

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

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

 <script id="books" type="text/html"> Your markup here... </script> <script id="about" type="text/html"> Your markup here... </script> 
+4
source

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


All Articles