0

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!

Donald T
  • 10,234
  • 17
  • 63
  • 91

2 Answers2

2

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.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
0

You have a typo, do this on the line:

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

The $ was missing before this

js1568
  • 7,012
  • 2
  • 27
  • 47
  • Unfortunately, this doesn't fix the problem. Apparently "this" and "$(this)" are the same in this context. Thanks though. – Donald T Jun 17 '11 at 17:18
  • @Jack: Why not use just `this[0].addJSONData(data);`? The real problem which you has could be not the line. I described how I see the problem in my answer. – Oleg Jun 18 '11 at 06:50