1

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

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

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

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

链接到小提琴

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")
  });

其次,我会

4

1 回答 1

0

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

要添加一个类,您可以简单地使用this.$el.find("#container").addClass("class").

这是更新的小提琴。

于 2013-10-04T02:38:29.633 回答