Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

filtering - Prevent DataTables custom filter from affecting all tables on a page

When we add a custom filter to DataTables:

$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
  ...
})

it works as expected on one table. However, if we have multiple tables on the same page, all filters affects all tables. How to create custom filters that only affect a specific table?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All custom filters works globally because $.fn.dataTable.ext.search is a global array any DataTable on a page takes into consideration when they are redrawn. There is no way around it, it is simply how DT is designed.

However, by using DT's plug-in architecture and simply hook into the relevant events, it is easy to replace the global array with local custom filters when needed, if any :

$.fn.dataTable.Api.register('filter.push', function(fn, draw) {
  if (!this.__customFilters) {
    var filters = this.__customFilters = [] 
    this.on('mousedown preDraw.dt', function() {
      $.fn.dataTable.ext.search = filters
    })
  }
  this.__customFilters.push(fn)
  $.fn.dataTable.ext.search = this.__customFilters 
  this.draw()
})

$.fn.dataTable.Api.register('filter.pop', function() {
  if (!this.__customFilters) return
  this.__customFilters.pop()
})

Thats it. Now, if you have a page with multiple DataTables, and you want a custom filter to work for one specific table only :

table.filter.push(function(settings, data, dataIndex) {
  ...
})

If you want to remove the filter table.filter.pop()

Here is a demo with three tables on the same page, each of them having their own custom filter implemented -> http://jsfiddle.net/gc4ow8yr/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...