如何从主干中的视图呈现视图.js

How to render a view from a view in backbone.js

本文关键字:视图 js      更新时间:2023-09-26

我尝试初始化视图加载,然后将事件侦听器附加到初始视图中的链接,以便当有人单击该链接时,文档正文将替换为不同的主干.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")
  });

其次,我会

我认为定位"正文"的问题在于您还覆盖了脚本模板标记。 之后,下划线找不到模板,从而导致错误。 请尝试改为定位容器。

要添加类,只需使用 this.$el.find("#container").addClass("class") 即可。

这是更新的小提琴。