Javascript 获取未捕获类型错误:对象#<;对象>;没有方法';获取';当我尝试在模板中显示数据时
我遇到了获取未捕获类型错误的问题:当我尝试在模板中显示数据时,对象#没有方法“get”: 模板:Javascript 获取未捕获类型错误:对象#<;对象>;没有方法';获取';当我尝试在模板中显示数据时,javascript,backbone.js,underscore.js,Javascript,Backbone.js,Underscore.js,我遇到了获取未捕获类型错误的问题:当我尝试在模板中显示数据时,对象#没有方法“get”: 模板: <script type="text/template" id="class-template"> <table class="table striped"></table> <thead> <tr> &
<script type="text/template" id="class-template">
<table class="table striped"></table>
<thead>
<tr>
<th>Picture</th>
<th>First Name</th>
<th>Last Name</th>
<th>Role</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<% _.each(users,function(user){ %>
<tr>
<td><%= user.get('picUrl') %></td>
<td><%= user.get('firstName') %></td>
<td><%= user.get('lastLame') %></td>
<td><%= user.get('role') %></td>
<td><%= user.get('email') %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
视图:
我能够看到从fetch调用返回的数据,因此我知道我正在返回数据。当我将它发送到模板时,它似乎都崩溃了。提前感谢您的帮助 不应该在脚本模板上执行get(),而应该只传递原始属性,而不是传递整个模型 我意识到,您还必须更改模板,但通过这种方式抽象模板,并在模板本身之外执行循环,可以更好地处理错误。这也将使您的代码模块化,更容易调试 视图: 模板应该是:
<td><%- picUrl %></td>
<td><%- firstName %></td>
...
...
您在哪里使用它的用户了吗?或者在使用脚本之前编写脚本。我添加了一个调试器语句,如下所示:我将控制台日志添加到模板中,但它们从未运行过,看起来错误可能在CALL中的某个地方。我担心这会使$el
中保留集合的最后一个用户的html。如果您为空()呈现前的内容。它是否会多次运行模板并在每次运行时运行一个新表?您可以使用this.model.bind('change',this.render,this))代码>因此只有在更改模型时才会刷新和创建视图。这也是为每个模型创建一个主集合
视图和另一个视图的一个很好的理由,这样您就只能对特定的模型
更改进行操作。对于多次运行的模板,我会考虑预编译它们(不一定是服务器端)。我通常做的是创建一个数组并提前存储预编译模板,以便在需要时调用预编译函数。
var ShowClass = Backbone.View.extend({
el: '.page',
initialize: function() {
_.bindAll(this); //Make all methods in this class have `this` bound to this class
},
template: _.template($('#class-template').html()),
render: function() {
var users = new Users();
console.log('calling fetch');
users.fetch();
users.on("reset", function(users){
console.log('rendering with data:'+users.models[0].get('firstName'));
this.$el.html(this.template({users:users.models}));
console.log('finished');
}, this);
}
});
users.on("reset", function(users){
_.each(users, function (user) {
var data = user.toJSON();
this.$el.html(this.template({
picUrl: data.picUrl,
firstName: data.firstName }));
}, this);
<td><%- picUrl %></td>
<td><%- firstName %></td>
...