2015-10-22 34 views
0

我想做一个JSON调用并列出它与骨干的项目。我得到的项背成功和我能够确认它们是否可以使用控制台日志,但是当我尝试将它们传递到我的模板,我得到一个错误说对象没有传递到模板中的骨干

"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>

回答

2

您在下划线模板使用可变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> 
+0

这仍然不起作用。我也尝试扔入一个简单的虚拟对象,仍然得到相同的错误。由于某种原因没有任何东西传到模板 – user3417966

+2

@ user3417966:[从Underscore 1.7开始](http://stackoverflow.com/a/25881231/479863),你不能说'h = _.template(tmpl,variables )'',你必须't = _.template(tmpl); h = t(变量)'现在。所以'template'实际上是你的代码中的一个函数,当你使用'。el。时,jQuery正在执行那个函数([但不包括期望的参数](http://stackoverflow.com/a/26367958/479863))。 HTML(模板)'。 –

+0

现在有效,谢谢! – user3417966