Backbone js auto refresh / reload collection from the server and browsing with the collection

New to Trunk, please bring my not-so-beautiful javascript base 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 into the $ ('# students') container.

But I would like to automatically reload the collection from the server and view every few seconds. Any help would be appreciated.

+7
source share
1 answer

Now you need two more things:

First: Report your update when the collection changes. This may be a revised version of your initialization 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 update your view when a new item is added to your collection. Note: this will redisplay the whole #students section. This is better if you write a separate method that will just introduce a new DOM element.

Secondly: you need a way to get new data from the server. Once you receive it, you simply add them to your collection. You can use the fetch () methods of your collection, for example:

 collection.fetch(); 

or you can manually enter if you received them using non-subscription ajax calls:

 collection.add(newData); 

As you wanted to delay a few seconds between showing each load and showing, you can use the debounce method from the underline library, which is already a dependency for your spine,

+12
source

All Articles