骨干+把手

时间:2016-07-07 12:33:18

标签: javascript backbone.js handlebars.js

我是骨干和把手的新手,并试图模仿一个简单的场景。 我有两个htm页面:

的index.htm:

<div id="home">

  <h1 align="center">Music Paradise</h1>
  <div id="navigation" align="center">
    <p align="center">Search for bands of your choice</p>
    <a href="#/SearchBands">Search Bands</a>
    <p align="center">Search for concerts of your choice</p>
    <a href="#/SearchConcerts">Search Concerts</a> 
  </div> 
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript" src="../js/backbone.js"></script>
<script type="text/javascript" src="../js/route.js"></script>

路由器页面:

var BandView = Backbone.View.extend({
      template: Handlebars.compile( $("#SearchBands-template").html() ),      
      initialize: function () {
          this.render();
      },

      render: function () {
          this.$el.html(this.template({greeting:"Welcome to Search Bands Feature!"}));

      }
  });


var ConcertView = Backbone.View.extend({
      template: Handlebars.compile( $("#SearchBands-template").html() ),      
      initialize: function () {
          this.render();
      },
      render: function () {
         this.$el.html(this.template({content:"Welcome to Search Concerts Feature!"}));

      }
    });


  var AppRouter = Backbone.Router.extend({
      routes: {          
          'SearchBands': 'bandRoute',
          'SearchConcerts': 'concertRoute',          
      },
      bandRoute: function () {
          var bandView = new BandView();          
          $("#data").html(bandView.el);
      },
      concertRoute: function () {
          var concertView = new ConcertView();          
          $("#data").html(concertView.el);
      }
  });

  var appRouter = new AppRouter();
  Backbone.history.start();

以及应将结果路由到的第三个htm页面。

searchBands.htm

<div id="home">

  <h1 align="center">Music Paradise</h1>

<div id="data">
</div>

  <script type="text/template" id="SearchBands-template">
      <h1>Please Search Bands</h1>
     {{ greeting }}
  </script>



  <script type="text/template" id="SearchConcerts-template">
      <h1>Please Search Concerts</h1>
      {{ content }}
  </script>


</div>

我收到以下错误: handlebars.min.js:27未捕获错误:您必须将字符串或Handlebars AST传递给Handlebars.compile。你通过了undefined。

我想这是由于route.js仍然不了解searchBands.htm,不知何故我需要先加载searchBands.htm。

感谢。

1 个答案:

答案 0 :(得分:1)

Backbone及其尝试使用的基于散列的路由专为单页应用程序而设计。

在运行应用程序脚本之前,<script>本身的index.html标签应该可用于jQuery,以便通过id选择器找到它。

如果您想将模板保存在不同的HTML文件中,那么您应该以某种方式使用AJAX加载它们并将它们传递给把手。如何做到这一点取决于更广泛的应用程序结构,例如,如果你使用RequireJS,你可以使用它的文本插件,或者你可以使用jQuery的load方法。