簡體   English   中英

骨干模板不顯示

[英]Backbone template doesn't show

我根據示例開始學習Backbone.js,以更改特定div的內容。 但是內容沒有顯示。

根據該示例,我創建了Backbone.View.js:

Backbone.View = Backbone.View.extend({
  remove: function() {
      $(this.el).empty().detach();
      return this;
  }
});

然后是我的app.js(組合視圖和路由器)

var appView = Backbone.View.extend({
  initialize: function(options){
      this.template = options.template;
  },

  render: function(){
     var content = $(this.template).html();
     $(this.el).html(content);
     return this;
  }
});

 var AppRouter = Backbone.Router.extend ({

    initialize: function(el) {
        this.el = el;
        this.homePage  = new appView({template: '#home'});
        this.viewPage = new appView({template: '#view'});
        this.notFoundPage = new appView({template: '#not-found'});
    },

    routes: {
        ''     : 'home',
        'view' : 'viewImage',
        'else' : 'notFound'
    },

    currentView: null,

    switchView: function(view){
        if(this.currentView){
            this.currentView.remove();
        }
        this.$el.html(view.el);
        view.render();
        this.currentView = view;
    },

    home: function(){
        this.switchView(this.homePage);
    },
    viewImage: function(){
        this.switchView(this.viewPage);
    },
    notFound: function() {
        this.switchView(this.notFoundView);
    }
});

和我的HTML部分

    <div class="page">
        <h1>HELLO BACKBONES</h1>
          <div>
            <a href="#home">home</a>
          </div>
          <div>
            <a href="#view">view</a>
          </div>
        <div id="content" class="content" style="background-color: red;"></div>
    </div>

    <!-- Templates -->
    <script id="home" type="text/html">
        <div>
            <p>I am the Home Page Content</p>
        </div>
    </script>

    <script id="view" type="text/html">
         <div>
            <p>I am the View Page Content</p>
        </div>
    </script>

    <script id="not-found" type="text/html">
         <div>
            <p>Content does not exist</p>
        </div>
    </script>

我也想不通如何從路由器調用視圖,如果它在不同的路徑

問題出在您的方法switchView 您嘗試使用this.$el但未定義

您應該改用this.el

switchView: function(view){
    if(this.currentView){
        this.currentView.remove();
    }
    this.el.html(view.el);
    view.render();
    this.currentView = view;
}

要啟動您的應用程序,請不要忘記在腳本末尾添加以下代碼:

var router = new AppRouter($('#content'));
Backbone.history.start();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM