如何从backbone.js中的视图呈现视图

时间:2013-10-04 02:05:52

标签: javascript jquery backbone.js

我尝试初始化视图onload,然后将事件监听器附加到初始视图中的链接,这样当有人单击该链接时,文档正文将替换为不同的backbone.js视图。

我非常接近,但我一直遇到js错误:

Uncaught TypeError: Cannot call method 'replace' of undefined underscore-min.js:5

其次,在呈现视图后,如何在#blog中向#container添加一个类?你会在小提琴中看到我已经编写了CSS和新课程。

Link to Fiddle

HTML

<script type="text/template" id="index">
    <a href="" id="thing">click here</a>
</script>

<script type="text/template" id="blog">
    <div id="container"><p>Hello world.</p></div>
</script>

JS

    BlogView = Backbone.View.extend({
        initialize: function(){},
        render: function(){
            var template = _.template( $("#blog").html(), {} );
            this.$el.html( template );
        }
    });

    IndexView = Backbone.View.extend({
      initialize: function () {
          this.render();
      },
      render: function () {
          var template = _.template($("#index").html(), {});
          this.$el.html(template);
      },
      events: {
          "click a": "initBlogView"
      },
      initBlogView: function () {
          blog_view.render();
          return false;
      }
  });

  var blog_view = new BlogView({ el: $("body") });

  var index_view = new IndexView({
      el: $("body")
  });

其次,我会

1 个答案:

答案 0 :(得分:0)

我认为定位“正文”的问题在于您还要覆盖脚本模板标记。之后,Underscore无法找到模板,从而导致错误。请尝试定位容器。

要添加课程,您只需使用this.$el.find("#container").addClass("class")

Here's the updated Fiddle.