这是我的 -6ren">
gpt4 book ai didi

javascript - Backbone 。我的 View 已为每个对象重写

转载 作者:行者123 更新时间:2023-12-03 08:48:10 25 4
gpt4 key购买 nike

这是我的 HTML

<div class="productsContainer">
<ul class="nav nav-tabs" role="tablist" id="products">
</ul>
</div>
<script type="text/template" id="productsTemplate">
<li role="presentation" class="active"><a href="#<%= title %>" aria-controls="<%= title %>" role="tab" data-toggle="tab">
<%= title %>
</a></li>
</script>

这是我的 JS:

var Product = Backbone.Model.extend();
var Products = Backbone.Collection.extend({
model: Product,
url: '/*server url*/'
});

var ProductView = Backbone.View.extend({
initialize:function(options){
console.log(this.el);
return this.render();
},
el:'div.productsContainer ul',

template: _.template( $('#productsTemplate').html() ),

render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
},

renderEL: function(item){
var productView = new ProductView({
model: item
});
}
});


var ProductsView = Backbone.View.extend({

el:'div.productsContainer ul',

initialize:function(options){
this.collection = new Products(options.collection);
this.collection.fetch({reset:true, add:true});
this.listenTo( this.collection, 'reset', this.render);
this.listenTo( this.collection, 'add', this.renderProduct);
return this;
},
render:function(){
this.collection.each(function(item){
this.renderProduct(item);
}, this);

return this;
},

renderProduct: function(item){
var productView = new ProductView({
model: item
});

this.$el.append(productView.render().$el);
}
});

var productsView = new ProductsView({});
$("div.productsContainer").append(productsView.render().$el);

当我在“var ProductView = Backbone.View.extend({})”tagName:'li'中使用时,脚本已添加每个对象,但我得到'li''li''/li''/li' ....,所以我使用了 el:''ul'....但脚本重写了一个元素“li”中的每个对象。我如何实现我的脚本,为每个对象添加一个新标签?

最佳答案

您得到 'li''li''/li''/li' 因为 ProductView 自动创建 'li' 标签(tagName: 'li')并且您的模板还包含 'li' ,它被附加/插入到 'li' 中'。只需从模板中删除“li”并仅保留“a”即可。

如果“li”应具有任何类/属性,请在构造 View ( http://backbonejs.org/#View-constructor ) 时使用“className”(className:'active')或“attributes”(属性:{role: 'presentation'})。

关于javascript - Backbone 。我的 View 已为每个对象重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com