[英]Accessing model attributes from Backbone view Underscore template
我有一个Backbone.js视图,看起来像这样:
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
视图,如下所示:
$(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>');
然后,当您准备渲染视图时,请稍后使用数据调用此函数:
this.$el.html(this.compiledTemplate(this.model.toJSON()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.