I have a Web Application that currently uses JQGrid but I’m trying to introduce Backbone.js to improve code organization. What I’m trying to do is get data from the server using a Collection, and then add the JSON information to my defined JQGrid but I can’t get it to work. My JQGrid is defined like this:
var tareasHumanasTable = $("#grillaTH").jqGrid({
datatype: 'local',
height: 'auto',
colNames:[ colNames...],
colModel:[ colModel...]
}
And my Model and Collection are defined like this:
window.TareaHumana = Backbone.Model.extend();
window.TareaHumanaCollection = Backbone.Collection.extend({
model: TareaHumana,
url: "bandejaTareas/buscarTH"
});
I have a button that when clicked starts server communication. Now is doing this:
$(function(){
$("#botonBuscar").bind('click',function(){
var tareaHumanaList = new TareaHumanaCollection();
tareaHumanaList.fetch({data: $("#formBandejaTareas").serializeObject()});
//alert("tareaHumanaList.toJSON(): " + tareaHumanaList.toJSON());
tareaHumanaList.each(function(tareaHumana, i){
//alert("tareaHumana.toJSON(): " + tareaHumana.toJSON());
tareasHumanasTable.jqGrid('addRowData', (i + 1), tareaHumana.toJSON());
});
That code doesn’t work at all. With Firebug I verified that the server sends the data in the correct format but the code isn’t working. The weirdest thing is that when I uncomment the “alert(…)” lines everything starts to work.
The key is that
fetchis asynchronous. So if you immediately calleachafterfetchit’s probably your collection won’t be populated. You should usesuccesscallback. For example take a look at this answer.