在Backbone.js中加载模板

时间:2016-04-05 12:24:39

标签: backbone.js underscore.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>

1 个答案:

答案 0 :(得分:4)

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

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