将Sammy.js和Knockout.js与具有多个参数的模板一起使用

时间:2014-06-04 16:29:06

标签: templates knockout.js sammy.js

我有一个使用Sammy和Knockout的网站。我试图用Sammy将多个视图路由到不同的URL,但我遇到了一些困难。我需要传递data参数以及templateName参数。我怎样才能传递数据参数?我在下面提供了相关代码。

的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>

1 个答案:

答案 0 :(得分:0)

使用传递给get的回调函数

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

然后你应该能够附加查询字符串params并从get函数中读取它们。

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