New to Backbone , please bear my not so beautiful backbone javascript code.
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.
But I would like to auto reload the collection from server and the view every a few seconds. Any help would be appreciated.
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.
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:
collection.fetch();
or, you can manually inject if you've received them using non-backbone ajax calls:
collection.add(newData);
As you wanted to delay few seconds between showing each load and show, you can use the debounce method from underscore library which is already a dependency for your backbone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With