0

I have these blocks in my code:

$.fn.dataTableExt.afnSortData['dom-text'] = function (oSettings, iColumn) {
    var aData = [];
    $('td:eq(' + iColumn + ') input', oSettings.oApi._fnGetTrNodes(oSettings)).each(function () {
        aData.push(this.value);
    });
    return aData;
}

$.fn.dataTableExt.afnSortData['dom-data-rk'] = function (oSettings, iColumn) {
    var aData = [];
    $('td:eq(' + iColumn + ')', oSettings.oApi._fnGetTrNodes(oSettings)).each(function () {
        aData.push($(this).attr('data-rk'));
    });
    return aData;
}

What does it mean: $.fn.dataTableExt I am not familar with $.fn.

Also can I combine these two?

Angela
  • 3,269
  • 3
  • 22
  • 24

3 Answers3

1

The dom-text and dom-data-rk properties are different, so you can't combine them 100% into the same block. Also, the function implementations are slightly different:

  • 'td:eq(...) input' vs. 'td:eq(...)',
  • aData.push(this.value) vs aData.push($(this).attr('data-rk').

Using jQuery.extend:

$.extend($.fn.dataTableExt.afnSortData, {
  'dom-text': function(oSettings, iColumn) { ... },
  'dom-data-rk': function(oSettings, iColumn) { ... }
});
EthanB
  • 4,239
  • 1
  • 28
  • 46
1

What you can do is using $.each with an object that contains the differences. The general code path of each function can then be the same. But, given that the functions are already concise and that there are several differences, there is not really a much neater solution:

$.each({
  'dom-text': {
    selector: function(i) { return 'td:eq(' + i + ') input'; },
    item: function(elem) { return elem.value; }
  },
  'dom-data-rk': {
    selector: function(i) { return 'td:eq(' + i + ')'; },
    item: function(elem) { return $(elem).data('rk'); }
  }
}, function(key, descriptor) {
  $.fn.dataTableExt.afnSortData[key] = function(oSettings, iColumn) {
    var aData = [];

    $(oSettings.oApi._fnGetTrNodes(oSettings))
      .find(descriptor.selector(iColumn))
      .each(function () {
          aData.push(descriptor.item(this));
      });

    return aData;
  };
});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

Since they have different input and output, it would not be a good idea to combine them. From what I can see, the first one gets the input value of the designated column, and add them to an array. The second one gets the attribute name data-rk and add them to an array.

If you really must combine them, you can add the output to different lists, but they you'd have to use IFs statement to check which type of sort it is, which would be kind of ...

Jason Dam
  • 390
  • 1
  • 8