Javascript 主干。视图不显示。但是console.log可以看到我的对象吗
这是我的HTMLJavascript 主干。视图不显示。但是console.log可以看到我的对象吗,javascript,html,backbone.js,Javascript,Html,Backbone.js,这是我的HTML <script type="text/template" id="productTemplate"> <p><%= title %></p> <h1><%= title %></h1> <img src="<%= img %>" alt="<%= title %>" />
<script type="text/template" id="productTemplate">
<p><%= title %></p>
<h1><%= title %></h1>
<img src="<%= img %>" alt="<%= title %>" />
<p><%= text %></p>
</script>
log(this.model.toJSON());
有观点
对象{id:1,标题:“product1”,img:“img1.png”,文本:“lorem ipsum 1”}
对象{id:1,标题:“product1”,img:“img1.png”,文本:“lorem ipsum”
1“}
您的
$el
中有什么内容console.dir(this.$el)
@MysterX,jQuery.fn.init[1]@MysterX中没有$el,jQuery.fn.init[1]:0:li.product-container长度:1 proto:jQuery[0]您需要将集合追加到DOM中。这里是JSFIDLE,稍作修改以简化初始化(无需服务器调用)。还要注意,this.collection.fetch({reset:true})是异步的,所以在初始化函数中调用render时可能不会填充集合。并且您在collection.fetch之后注册了侦听器,因此它可能不会在重置事件时调用render。
var Product = Backbone.Model.extend();
var Products = Backbone.Collection.extend({
model: Product,
url: '/*there server url*/'
});
var ProductView = Backbone.View.extend({
tagName:'li',
className:'product-container',
initialize:function(){
this.render();
},
template: _.template( $('#productTemplate').html() ),
render: function () {
console.log(this.model.toJSON());
this.$el.html( this.template(this.model.toJSON()));
return this;
}
});
var Ajax = new Products();
var ProductsView = Backbone.View.extend({
tagName:'ul',
initialize:function(initialProduct){
this.collection = Ajax;
this.collection.fetch({reset: true});
this.render();
this.listenTo( this.collection, 'add', this.renderProduct );
this.listenTo( this.collection, 'reset', this.render );
},
render:function(){
this.collection.each(function(item){
this.renderProduct(item);
},this);
},
renderProduct: function(item){
var productView = new ProductView({
model:item
});
this.$el.append(productView.render(item));
}
});
$(function(){
var productsView = new ProductsView;
});