Browser Memory Usage Comparison: inline onClick vs. using JQuery .bind()

Solution 1:

Because you need not only a general solution with some container objects, but the solution for jqGrid I can suggest you one more way.

The problem is that jqGrid make already some onClick bindings. So you will not spend more resources if you just use existing in jqGrid event handler. Two event handler can be useful for you: onCellSelect and beforeSelectRow. To have mostly close behavior to what you currently have I suggest you to use beforeSelectRow event. It's advantage is that if the user will click on one from your custom buttons the row selection can stay unchanged. With the onCellSelect the row will be first selected and then the onCellSelect event handler called.

You can define the columns with buttons like following

{ name: 'add', width: 18, sortable: false, search: false,
  formatter:function(){
      return "<span class='ui-icon ui-icon-plus'></span>"
  }}

In the code above I do use custom formatter of jqGrid, but without any event binding. The code of

beforeSelectRow: function (rowid, e) {
    var iCol = $.jgrid.getCellIndex(e.target);
    if (iCol >= firstButtonColumnIndex) {
        alert("rowid="+rowid+"\nButton name: "+buttonNames[iCol]);
    }

    // prevent row selection if one click on the button
    return (iCol >= firstButtonColumnIndex)? false: true;
}

where firstButtonColumnIndex = 8 and buttonNames = {8:'Add',9:'Edit',10:'Remove',11:'Details'}. In your code you can replace the alert to the corresponding function call.

If you want select the row always on the button click you can simplify the code till the following

onCellSelect: function (rowid,iCol/*,cellcontent,e*/) {
    if (iCol >= firstButtonColumnIndex) {
        alert("rowid="+rowid+"\nButton name: "+buttonNames[iCol]);
    }
}

In the way you use one existing click event handler bound to the whole table (see the source code) and just say jqGrid which handle you want to use.

I recommend you additionally always use gridview:true which speed up the building of jqGrid, but which can not be used if you use afterInsertRow function which you considered to use as an option.

You can see the demo here.

UPDATED: One more option which you have is to use formatter:'actions' see the demo prepared for the answer. If you look at the code of the 'actions' formatter is work mostly like your current code if you look at it from the event binding side.

UPDATED 2: The updated version of the code you can see here.

Solution 2:

You should use the .delegate() method to bind a single click handler for all elements ,through jQuery, to a parent element of all buttons.

For the different parameters you could use data- attributes to each element, and retrieve them with the .data() method.