Search code examples
templatesknockout.jssammy.js

Using Sammy.js and Knockout.js with Templates Having Multiple Parameters


I have a website using Sammy and Knockout. I am trying to route multiple views to different URLs with Sammy but I'm having some difficulty. I need to pass the data parameter as well as the templateName parameter. How would I be able to pass the data parameter? I've included relevant code below.

Javascript

    var View = function (title, templateName, data) {
        var self = this;
        this.title = title;
        this.templateName = templateName;
        this.data = data;
    };
    var viewModel = {
        views: ko.observableArray([
            new View("Home", "home", homeView),
            new View("Announcements", "announcements", announcementView),
            new View("Calendar", "calendar", monthView),
            new View("Contact Us", "contactus", contactView),
            new View("Events", "events", eventsView)
        ]),
        selectedView: ko.observable()
    };

    $.sammy(function () {
        this.get('#:templateName', function () {
        viewModel.selectedView(this.params);
        });
    }).run('#home');

vbhtml

   <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
       <div class="container">
           <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                </button>
                <a class="navbar-brand" href="#">Events</a>
           </div>

           <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav" data-bind="foreach: views">
                   <li data-bind="css: {active: $root.selectedView == $data"><a data-bind= "text: title, click: $root.selectedView " ></a></li>  
               </ul>
               <ul class="nav navbar-nav navbar-right">
                   <li><a href="#login-box" class="login-window">Login</a></li>
               </ul>
          </div>
       </div>
    </nav>
    <div data-bind="with: selectedView">
         <div data-bind="template: { name: templateName, data: data }"></div>
    </div>



    <script id="home" type="text/html">...</script>
    <script id="announcements" type="text/html">...</script>
    <script id="calendar" type="text/html">...</script>
    <script id="contactus" type="text/html">...</script>

Solution

  • Use the context parameter passed into the get's callback function

    this.get('#:templateName', function(context) {
        var params = context.params;
    });
    

    You should then be able to append querystring params and read them from the get function.

    .run('#home?param1=1&param2=2')