Demo - CollectionView Filtering

by Joel Parks

HTML

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.wijmo.com/5.latest/styles/wijmo.min.css">
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.min.js"></script>
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.input.min.js"></script>
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.grid.min.js"></script>
<script src="http://cdn.wijmo.com/5.latest/controls/wijmo.grid.filter.min.js"></script>
<div class="container">

  <h1>
    Chaining Filters
  </h1>

  <p>
    The <b>CollectionView.filter</b> property allows you
    to specify one filtering function for the collection.</p>
  <p>
    In some cases, you may want to use two or more .</p>
  <p>
    To see an example, choose one of the options:</p>

  <input id="theFilter" name="filter" placeholder="filter"/>    

  <p>
    Result (<span id="cnt"></span> items):
  </p>
  <div id="theGrid">
  </div>
</div>

CSS

.wj-flexgrid {
  max-height: 250px;
}
label {
  width: 100%
}

JavaScript

onload = function() {

	// create some random data
	var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(',');
  var data = [];
	for (var i = 0; i < 1000; i++) {
  	data.push({
    	id: i,
    	country: countries[i % countries.length],
    	downloads: Math.round(Math.random() * 20000),
    	sales: Math.random() * 10000,
    	expenses: Math.random() * 5000
  	});
	}
  
  // create a CollectionView based on the raw data
  var view = new wijmo.collections.CollectionView(data);
  
  // create a second CollectionView based on the first one
  var view2 = new wijmo.collections.CollectionView(view.items, {
  	collectionChanged: function(s) {
	  	var cnt = document.getElementById('cnt');
  	  cnt.textContent = wijmo.format('{length:n0}', s.items)
    }
  });

  // bind a grid to the second CollectionView
  var theGrid = new wijmo.grid.FlexGrid('#theGrid', {
  	itemsSource: view2,
    showAlternatingRows: false,
    headersVisibility: 'Column'
  });
  
  // add a filter to the grid (will act on the second CollectionView)
  var f = new wijmo.grid.filter.FlexGridFilter(theGrid);

	// update the filter on the first CollectionView when the text changes
  document.getElementById('theFilter').addEventListener('input', function(e) {
  
  	// update first CollectionView's filter
  	var filterText = e.target.value;
  	view.filter = function(item) {
    	return filterText 
      	? item.downloads.toString().indexOf(filterText) > -1
        : true;
    }
    
    // update second collection view's sourceCollection
    view2.sourceCollection = view.items;
  });
}