我有一个如下所示的 Backbone.js View :
var StreamV = Backbone.View.extend({
tagName: 'div',
className: 'stream',
events: { },
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
},
template: function (data) {
console.log(data);
if (data.mime_type.match(/^audio\//)) {
return _.template('<audio controls><source src="<%= resource_uri %>">No sound</audio>', data);
} else {
// FIXME Do what?
return _.template();
}
},
});
相应的模型如下所示:
var StreamM = Backbone.Model.extend({
url: function () {
return (this.id) ? '/streams/' + this.id : '/streams';
}
});
我正在尝试实例化 StreamV
View ,如下所示:
$(document).ready(function () {
var streams = new StreamsC;
streams.fetch({success: function (coll, resp, opts) {
var mp3 = coll.findWhere({mime_type: 'audio/mp3'});
if (mp3) {
var mp3view = new StreamV({el: $('#streams'),
model: mp3});
mp3view.render();
} else {
$('#streams').html('No audio/mp3 stream available.');
}
}});
});
我发现我的 Underscore 模板没有获取我发送的数据。它说:
ReferenceError: resource_uri is not defined
((__t=( resource_uri ))==null?'':__t)+
我尝试更改 _.template
调用以提供具有 resource_uri
属性集的文字对象,但出现了相同的错误。
我通过提供一个对象作为 _.template
的第二个参数来做正确的事情吗?
最佳答案
Underscore 模板函数返回一个稍后用数据调用的函数。它的第二个参数不是要插入的数据,而是设置对象。
来自下划线文档:
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"
在您的情况下,您首先要像这样编译模板:
this.compiledTemplate = _.template('<audio controls><source src="<%= resource_uri %>">No sound</audio>');
然后,当您准备好渲染 View 时,使用数据调用此函数:
this.$el.html(this.compiledTemplate(this.model.toJSON()))
关于javascript - 从 Backbone View 下划线模板访问模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26297607/