骨干模板没有显示

时间:2014-01-16 08:17:14

标签: javascript jquery backbone.js

我开始在this示例后学习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>

此外,我无法弄清楚如果路由器处于不同的路径中,如何从路由器调用视图

1 个答案:

答案 0 :(得分:1)

问题在于您的方法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();