我有大量的json对象,我通过搜索功能检索,虽然取决于搜索字符串,但输出可以达到我填充到列表中的数千个数组。在移动环境中,一旦我为每个对象添加了touchmove,touchstart和touchend,这就变得麻烦和消耗内存。我找到了解决这个问题的方法,即使用backbone.js显示对象的最小方式,以及使用按钮等按钮,这可能会变得健壮。虽然我不知道该如何去做。这是没有按钮的工作示例。我该怎么做呢?
<script>
//model - define value objects.
var Client = Backbone.Model.extend({
defaults: {
name: 'cole',
age: '12'
}
});
//collection - load json
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: './json/test.json',
//override parse due to json format. point to "items"
parse: function (response, xhr) {
return response.items;
}
});
//view. init collection. listen for data to be loaded. render.
var ClientView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.fetch();
},
render: function () {
//append to html here ...
//alert(this.collection.at(0).get("name"));
//alert(this.collection.length)
for (var i = 0; i < this.collection.length; i++) {
$('#append-el').append('<li>' + this.collection.at([i]).get("name") + '; ' + this.collection.at([i]).get("age") + '</li>')
}
}
});
var clientView = new ClientView();
</script>
<div id = "append-el"></div>
答案 0 :(得分:1)
如果我理解你,那么这应该有效:
var ClientView = Backbone.View.extend({
el: '#append-el',
events: {
'click button': 'onButtonClick'
},
initialize: function() {
_.bindAll(this);
this.collection = new ClientCollection();
this.collection.bind("reset", this.renderClients);
this.render();
},
render: function() {
//append to html here ...
this.$el.append('<button type="button">Fetch clients</button><ul class="clients"></ul>');
},
renderClients: function() {
var $ul = this.$('ul.clients').empty();
this.collection.each(function(client) {
$ul.append('<li>' + client.get("name") + '; ' + client.get("age") + '</li>');
});
},
onButtonClick: function(e) {
this.collection.fetch();
}
});
答案 1 :(得分:1)
在视图中添加一个事件监听器,指向带有事件哈希的按钮,类似这样的
,events {
"click #buttonID" : "fillCollection"// <- this is a method name
}
然后创建此方法并触发collection.fetch
,就像这样
,fillCollection: function(){
this.collection.fetch();
}
答案 2 :(得分:0)
我建议不要一次获取数千件物品。限制为100最多200百。然后我会开始听清单上的滚动,根据需要获取剩余的项目(一旦用户接近滚动区域的末尾,你就可以自动加载它们,或者只是在底部放置一个“加载更多”按钮)
Backbone有几个paginator插件,你可以简单地限制render()函数中渲染元素的数量。