javascript-Backbone.js集合视图呈现重复项
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-Backbone.js集合视图呈现重复项,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2017字,纯文字阅读大概需要3分钟。
内容图文
![javascript-Backbone.js集合视图呈现重复项](/upload/InfoBanner/zyjiaocheng/674/c4b25edd72c840e5b39f0e25e4bc0683.jpg)
在我的Backbone.js应用程序中,我需要能够在集合中现有项目之间插入新项目.到目前为止,我在网络上发现的所有示例似乎都假定应该将新项目附加到集合的末尾.这对我的目的不起作用,因此我选择在添加新项目时重新呈现整个集合.
但是,原始项目不会从视图中删除.而是将一组重复的项目附加到列表的末尾.我可以通过使用jQuery在渲染之前清除项目来解决此问题,但这似乎是错误的.
这是我现在所拥有的:
Item = Backbone.Model.extend({
price: null,
});
Items = Backbone.Collection.extend({
model: Item,
initialize: function () {
this.add(new Item({ price: '$0.50' }));
this.add(new Item({ price: '$0.60' }));
this.add(new Item({ price: '$0.70' }));
}
});
ItemView = Backbone.View.extend({
tagName: 'li',
initialize: function () {
this.model.bind('change', this.render, this);
},
render: function () {
var item_template = _.template($('#item-template').html(), { item: this.model });
this.$el.html(item_template);
return this;
},
events: {
"click .copy-item": "copyItem",
},
copyItem: function (event) {
var index = itemlistview.collection.indexOf(this.model);
itemlistview.collection.add(new Item, { at: index + 1 });
},
});
ItemListView = Backbone.View.extend({
el: '#item-rows',
initialize: function () {
_.bindAll(this);
this.collection = new Items();
this.collection.bind('add', this.render);
this.render();
},
render: function () {
// It works if I uncomment the line below
//$('.item-row').remove();
var self = this;
this.collection.each(function (item) {
self.$el.append(new ItemView({ model: item }).render().el);
});
return this;
},
});
var itemlistview = new ItemListView;
这是jsFiddle演示此问题的信息.
有没有更好的方法来解决这个问题?
解决方法:
重新渲染整个过程时,确实需要清除旧的渲染输入.
修改后的ItemListView
ItemListView = Backbone.View.extend({
el: '#item-rows',
initialize: function () {
_.bindAll(this);
this.collection = new Items();
this.collection.bind('add', this.render);
this.render();
},
render: function () {
var self = this;
this.$el.empty()
this.collection.each(function (item) {
self.$el.append(new ItemView({ model: item }).render().el);
});
return this;
},
});
内容总结
以上是互联网集市为您收集整理的javascript-Backbone.js集合视图呈现重复项全部内容,希望文章能够帮你解决javascript-Backbone.js集合视图呈现重复项所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。