对象未传递到 backbone 中的模板

Object not passing down to template in backbone

我正在尝试进行 JSON 调用并使用 backbone 列出其中的项目。我成功取回了这些项目,并且能够通过控制台日志确认它们可用,但是当我尝试将它们传递到我的模板时,我收到一条错误消息

"Uncaught ReferenceError: quotes is not defined"

我的代码:

var Quotes = Backbone.Collection.extend({
  url: '/quotes.json'
});

var UserListView = Backbone.View.extend({
  el: '.quote-list',
  render: function() {
    var that = this;
    var quotes = new Quotes();
    quotes.fetch({
      success: function(quotes) {
        var variables = {
          search: "search"
        };
        var template = _.template($('#quotes-template').html(), variables);
        console.log(template)
        that.$el.html(template);
      }
    })
  }
});

var Router = Backbone.Router.extend({
  routes: {
    "": "home"
  }
});

$(document).ready(function() {
  var userListView = new UserListView;
  var router = new Router;
  router.on('route:home', function() {
    //render user list
    userListView.render();
  });

  Backbone.history.start();

})
<body>
  <div class="quote-list"></div>

  <script type="text/template" id="quotes-template">
    <% _.each(quotes, function(quote) { %>
      <ul>
        <li>
          <%=quote.source %>
        </li>
        <li>
          <%=quote.context %>
        </li>
      </ul>
      <% }); %>
  </script>
  <script src="js/app.js"></script>
</body>

您正在下划线模板中使用变量 quotes,但您传递给 _.template() 的数据不包含 quotes

您的代码应该是:

quotes.fetch({
  /*---------------collection----------------*/
  /*-------------------v----------------*/
  success: function(quotes, response, options) {
    var variables = {
      search: "search"
    }; // ...?
    var template = _.template($('#quotes-template').html(), {
      quotes: quotes
    });
    that.$el.html(template);
  }
});

由于成功回调中的第一个参数 quotesBackbone.Collection,您可能还想按如下方式更改模板,否则您可以传递第二个参数,即实际响应至 _.templte().

<body>
  <div class="quote-list"></div>

  <script type="text/template" id="quotes-template">
    <% _.each(quotes.models, function(quote) { %>
      <ul>
        <li>
          <%=quote.get("source") %>
        </li>
        <li>
          <%=quote.get("context") %>
        </li>
      </ul>
      <% }); %>
  </script>
  <script src="js/app.js"></script>
</body>