【问题标题】:Knockout.js url routingKnockout.js url 路由
【发布时间】:2012-02-11 18:27:10
【问题描述】:

我做了我的第一个 knockout.js 应用程序http://jsfiddle.net/Pqs7e/

对于显示应用程序部分(书籍部分,关于部分),我使用 jquery $("#id").show()。我觉得这不是正确的方法。如何通过viewmodel的机制做到这一点?

【问题讨论】:

    标签: knockout.js sammy.js


    【解决方案1】:

    另一种方法是使用模板:

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

    然后你的部分可以像这样定义在某个地方(在同一个文件或其他地方):

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

    【讨论】:

      【解决方案2】:

      我会使用特殊的 state observable 来识别要显示的 div:

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

      然后你就这样绑定它:

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

      并像这样在状态之间切换:

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

      【讨论】:

        猜你喜欢
        • 2012-12-18
        • 1970-01-01
        • 2014-08-08
        • 2011-10-22
        • 2020-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多