[StackOverflow] Backbone.js and jqGrid

A simple example using Backbone.JS and jqGrid. This example add each model present on the collection to the jqGrid.

by Exceeder

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.layout.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.tablednd.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.contextmenu.js"></script>
<link rel="stylesheet" href="http://www.trirand.com/blog/jqgrid/themes/redmond/jquery-ui-1.8.1.custom.css">
<link rel="stylesheet" href="http://www.trirand.com/blog/jqgrid/themes/ui.jqgrid.css">
<link rel="stylesheet" href="http://www.trirand.com/blog/jqgrid/themes/ui.multiselect.css">
<div class="mygrid"> 
<table id="dogsList"></table>
</div>    

<button id="switch">switch</button>

CSS

.mygrid .ui-jqgrid.ui-widget-content {
 border:#ccc 1px solid;
 background:#eee;   
}

JavaScript

// Create the table
var dogsTable = jQuery("#dogsList").jqGrid({ 
    datatype: 'local',
    width:'100%',
    autowidth:true,
    colNames:['name', 'breed'], 
    colModel:[  {name:'name', align:'left'},
                {name:'breed', align:'left'}],
    loadComplete : function(data) {
        //alert('grid loading completed ' + data);
    },
    loadError : function(xhr, status, error) {
        alert('grid loading error' + error);
    }
});

// Create the collection
var Collection = Backbone.Collection.extend();

// Init the collection
var dogs = new Collection([
    {name:"Jane",breed:"Great Dane"},
    {name:"Rocky",breed:"golden Retriver"},
    {name:"Jim",breed:"Lab"}
]);

// Init the collection 2
var cats = new Collection([
    {name:"Meow",breed:"Siameeze"},
    {name:"Kiss",breed:"Blue Russian"},
    {name:"Smoke",breed:"Experimental"}
]);

// For each dog, add a row in the table
dogs.each(function (dog, i) {
    dogsTable.jqGrid('addRowData', (i + 1), dog.toJSON());
});

$('#switch').click(function() {
    dogsTable.jqGrid('clearGridData');
    cats.each(function (cat, i) {
        dogsTable.jqGrid('addRowData', (i + 1), cat.toJSON());
    });
});