user1947287
user1947287

Reputation: 15

Sammy.js Routing Not Propagating to Knockout.js

I am trying to get a simple routing mechanism working with Knockout and Sammy. Although I can get it to work with just JQuery, I cannot get it to work with Sammy and Knockout. Here is the code:

$(function() {
    var myViewModel = {
        viewDiv: ko.observable("home") };

    var app = $.sammy(function() {
        this.get("#/", function() { myViewModel.viewDiv = "home";});
        this.get("#/div1", function() { myViewModel.viewDiv = "div1";});
        this.get("#/div2", function() { myViewModel.viewDiv = "div2";});
        this.get("#/div3", function() { myViewModel.viewDiv = "div3";});
    });
    $(function() { app.run("#/") });

    ko.applyBindings(myViewModel);
});

Here is the markup:

<div id="main">
    <ul id="link">
        <li><a href="#/div1">Div1</a></li>
        <li><a href="#/div2">Div2</a></li>
        <li><a href="#/div3">Div3</a></li>
        <li><a href="#/">Home</a></li>
    </ul>
    <p>viewDiv:<span data-bind="text: this.viewDiv"></span></p>
</div>
<div id="content">
    <div id="home"  data-bind="visible: this.viewDiv=='home'">
        <h2>Home</h2>
    </div>
    <div id="div1"  data-bind="visible: this.viewDiv=='div1'">
        <h2>First Div</h2>
    </div>
    <div id="div2"  data-bind="visible: this.viewDiv=='div2'">
        <h2>Second Div</h2>
    </div>
    <div id="div3"  data-bind="visible: this.viewDiv=='div3'">
        <h2>Third Div</h2>
    </div>
</div>

The URL changes as expected, but all divs I want to show or hide remain hidden and the single data-bind to show the current div shows nothing. I also had console log statements inside the Sammy routes. These recorded the divs as expected. I am probably missing something simple. Can anyone help? Thanks in advance!

Upvotes: 0

Views: 663

Answers (1)

jjperezaguinaga
jjperezaguinaga

Reputation: 2482

In KnockoutJS we update observables this way:

myViewModel.viewDiv("home")

and not like this

myViewModel.viewDiv = "home"

Upvotes: 2

Related Questions