jQuery Backbone js 从服务器自动刷新/重新加载集合并使用集合更新视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15424387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone js auto refresh/reload collection from server and update view with collection
提问by wwli
New to Backbone , please bear my not so beautiful backbone javascript code.
Backbone 新手,请承担我不那么漂亮的骨干 javascript 代码。
This is my code
这是我的代码
var Schedule = Backbone.Model.extend({
initialize: function () {
console.log("initializing model");
}
});
var ScheduleCollection = Backbone.Collection.extend({
model: Schedule,
url: "<%=students_swimming_classschedules_path%>",
parse: function (resp) {
return resp;
},
});
var Schedules = Backbone.View.extend({
initialize: function () {
console.log("initializing view");
collection.on('add', this.render, this);
this.render();
},
render: function () {
for (var i = 0; i < collection.length; i++) {
s += "<tr><td>" + collection.models[i].get('account') + "</td><td>" + collection.models[i].get('status') + "</td></tr>";
}
this.$el.html(s);
},
})
var schedules = new Schedules({
el: $("#students")
});
window.setInterval(function () {
collection.fetch();
}, 2000);
This code works. And I can load all students to $('#students') container.
此代码有效。我可以将所有学生加载到 $('#students') 容器中。
But I would like to auto reload the collection from server and the view every a few seconds. Any help would be appreciated.
但我想每隔几秒钟从服务器和视图自动重新加载集合。任何帮助,将不胜感激。
回答by HungryCoder
You now need two more things:
你现在还需要两件事:
First: Tell your view to update when collection is changes. This could be the revised version of your initialize function in your view.
第一:告诉您的视图在集合更改时更新。在您看来,这可能是您的初始化函数的修订版。
initialize : function(){
console.log("initializing view");
collection.on('add', this.render, this);
collection.on('reset', this.render, this);
this.render();
},
this will refresh your view when new item is added to your collection.
Note: this will re-render whole #students
section. It's better if you write a separate method that will just inject the new item the DOM.
当新项目添加到您的收藏时,这将刷新您的视图。注意:这将重新渲染整个#students
部分。如果您编写一个单独的方法来将新项目注入 DOM,那就更好了。
Second: You need some way to fetch new data from server. As soon as you've received it, you just add them to your collection. You can use fetch()methods of your collection like:
第二:您需要某种方式从服务器获取新数据。收到后,您只需将它们添加到您的收藏中即可。您可以使用集合的fetch()方法,例如:
collection.fetch();
or, you can manually inject if you've received them using non-backbone ajax calls:
或者,如果您使用非主干 ajax 调用收到它们,则可以手动注入:
collection.add(newData);
As you wanted to delay few seconds between showing each load and show, you can use the debouncemethod from underscore library which is already a dependency for your backbone.
由于您想在显示每个加载和显示之间延迟几秒钟,您可以使用来自 underscore 库的debounce方法,该方法已经是您的主干的依赖项。