Click here for the js fiddle example
此模板应在集合中呈现新消息,即时尝试关注this tuorial 使用我自己的版本来呈现消息
<div id="messages" style="width: 600px">
</div>
<script type="text/template" id="messageTemplate">
<a href="#" class="list autoWidth <% if(has_been_read) { %> selected <% } %>">
<div class="list-content">
<img src="//www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=20774792" class="icon">
<div class="data">
<span class="item-title-secondary fg-gray"><b><%= sender %></b></span>
</div>
<span class="tertiary-text">
<%= message %>
</span>
</div>
</a>
</script>
这是Javascript
var messagesjson = [
{
id: 3,
message: "This is the message",
sender: "gabriel",
receiver: "gabriel",
has_been_read: false,
has_been_reported: false,
created_at: "2014-10-23T19:55:20+0200",
is_friend: false
},
{
id: 5,
message: "I'm loving this ",
sender: "gabriel",
receiver: "gabriel",
has_been_read: true,
has_been_reported: false,
created_at: "2014-10-23T20:02:34+0200",
is_friend: false
}];
var MessageModel = Backbone.Model.extend({
defaults:
{
id: 3,
message: "This is the message",
sender: "gabriel",
receiver: "gabriel",
has_been_read: false,
has_been_reported: false,
created_at: "2014-10-23T19:55:20+0200",
is_friend: false
}
});
var MessageView = Backbone.View.extend({
tagName: "div",
className: "listview",
template: $('#messageTemplate').html(),
render: function()
{
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});
var MessageCollection = Backbone.Collection.extend({
model: MessageModel
});
var MessageCollectionView = Backbone.View.extend({
el: $('#messages'),
initialize: function()
{
this.collection = new MessageCollection(messagesjson);
this.render();
},
render: function()
{
var that = this;
_.each(this.collection.models, function(item){
that.renderMessage(item);
},this);
},
renderMessage: function(item)
{
var messageview = MessageView({
model: item
});
this.$el.append(messageview.render().el);
}
});
var messagecollectionview = new MessageCollectionView();
而不是在“messages”模板中呈现消息,它不会呈现任何内容。
由于某种原因它说一个函数未定义但未能指出它 在骨干js代码之外,这是我添加的顺序 脚本
<script src="//jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
答案 0 :(得分:1)
您的代码中有错误:
var messageview = MessageView({
model: item
});
应该是
var messageview = new MessageView({
model: item
});
请参阅JSFiddle。