Donald T
Donald T

Reputation: 10647

Adding a function to jqGrid to add local JSON

I"m trying to create an additional function for jqGrid to simplify adding JSON data to a grid that uses local data. The following attempt works except for one line, which causes it to fail.

  $.fn.myrows = function(data) {
    $(this).clearGridData();
    $(this).jqGrid("setGridParam", {datatype: "json", loadonce: true});
    $("#" + (this).selector)[0].addJSONData(data); // PROBLEMATIC LINE
    $(this).jqGrid("setGridParam", {datatype: "local", loadonce: true});
  };

This function is then called as $("#myGrid").myrows(jsonDataObject);.

Note that these lines work when they are not inside this function.

Any ideas? Thanks!

Upvotes: 0

Views: 2592

Answers (2)

Oleg
Oleg

Reputation: 221997

In the answer on your previous question I tried to explain how to extend jqGrid to support new method. To tell the truth, I don't see what real advantage you will have from the jqGrid extending. Why not just define your function as

var myrows = function(grid,data) {
    // function body
};

and use it in the way:

myrows($("#myGrid"),jsonDataObject);

Much more important thing in my opinion is the implementation of what you need. Your current code have many disadvantages. If the grid has datatype: "local" then the local data paging can be used. The method addJSONData add all the data in the grid, so the page size can be broken.

If you have datatype: "local" and want to fill it with the data then the most effective way will be to set data parameter of the grid with respect of setGridParam and then just call $("#myGrid").trigger('reloadGrid',[{page:1}]) (see here).

Alternative you can use many other existing methods like addRowData which allows to add many rows of data at one method call.

If you get the JSON data from the server and thy to fill the grid with addJSONData method it will be really bad way. The versions of jqGrid starting with the version 3.5 has rich ways to customize the ajax request used. So it is strictly recommended that you don't use addJSONData in the case. See here for details.

Upvotes: 2

js1568
js1568

Reputation: 7032

You have a typo, do this on the line:

$("#" + $(this).selector)[0].addJSONData(data); // PROBLEMATIC LINE

The $ was missing before this

Upvotes: 0

Related Questions