我正在尝试使用骨干和下划线显示从ajax调用中获取的数据。
在FF中可行,但Chrome报告错误:Uncaught ReferenceError: data is not defined
。
(数据是指模板数据<% _.each(data, function(g) { %>
)
请参阅下面的代码。
系列:
define(['backbone','models/aModel'], function(Backbone, aModel) {
var aCollection = Backbone.Collection.extend({
url: "api/a",
model: aModel,
parse: function(response){
return response.data;
}
});
return aCollection;
});
模型:
define(['underscore', 'backbone'], function(_, Backbone) {
var aModel = Backbone.Model.extend({
urlRoot: 'api/b',
});
return aModel;
});
查看:
define(['jquery','underscore','backbone','models/aModel','collections/aCollection','text!templates/a.html'], function($, _, Backbone, aModel, aCollection, aTemplate){
var aView = Backbone.View.extend({
render: function() {
var self = this;
this.collection = new aCollection();
this.collection.fetch({
success: function(collection, response) {
self.$el.html(_.template(aTemplate, {data:self.collection.toJSON()}));
},
error: function(collection, response) {
alert("error");
}
});
return this;
},
});
return aView;
});
模板:
<% _.each(data, function(g) { %>
<tr>
<td><%=g.a%></td>
<td><%=g.b%></td>
<td><%=g.c%></td>
<td><%=g.d%></td>
</tr>
<% }); %>
数据:
{"data": [{"a":"1","b":"name1","c":"0000-00-00","d":x},{"a":"2","b":"name2","c":"0000-00-00","d":y}]}
这是解决方案 替换这个:
self.$el.html(_.template(aTemplate, {data:self.collection.toJSON()}));
用这个:
var compiledTemplate = _.template(aTemplate);
self.$el.html(compiledTemplate({data:self.collection.toJSON()}));
答案 0 :(得分:1)
我创建了一个JsFiddle来帮助。
这对谷歌Chrome有用。如果你遵循这个,我想你的问题将会得到解决。
$(function(){ var compiled = _.template($(“#template”)。html());
$("#here").html(compiled({ data: [ {"a":"1","b":"name1","c":"0000-00-00","d":"x"}, {"a":"2","b":"name2","c":"0000-00-00","d":"y"} ] }));
});
我猜不会使用chrome编译变量“aTemplate”。