正在 Backbone.js 中加载模板

Loading a template in Backbone.js

我处于 Backbonejs 的初学者水平。我正在尝试调用简单模板。但它给了我以下错误:

*Uncaught TypeError: Cannot read property 'replace' of undefined*

查看我为其创建的 plnk: http://plnkr.co/edit/fTcL4m?p=info

您也可以在这里找到代码:

<!DOCTYPE html>
<html>

  <head>
    <title>Loading a template</title>
  </head>

  <body>
    <h1>Loading a template</h1>

    <div id="search_container"></div>
<script data-require="jquery@2.2.0" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script data-require="underscore.js@1.8.3" data-semver="1.8.3" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script data-require="backbone.js@1.1.2" data-semver="1.1.2" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
    <script>
      SearchView = Backbone.View.extend({
        initialize: function(){
          this.render();
        },
        render: function(){
          var template = _.template($("#search_template").html(), {});
          this.el.html(template);
        }
      });
      var search_view = new SearchView({ el: $("#search_container") });
    </script>

    <script type="text/template" id="search_template">
      <label>Search</label>
      <input type="text" id="search_input" />
      <input type="button" id="search_button" value="Search" />
    </script>
  </body>

</html>

主要问题是脚本标签的顺序,

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

在您的脚本运行时不存在。你应该确保它确实如此,通过在包含代码的代码之前添加它,或者将你的代码包装在 $(function(){})

另一个问题是您应该使用 this.$el.html(template); 而不是 this.el.html(template);