Databinding w/RivetsJSs

by mrrodd

HTML

<script src="https://rawgithub.com/mikeric/rivets/v0.7.1/dist/rivets.bundled.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div id="divBrands">
  Name: <input type="text" rv-value="model.name" />
  <br/> 
  Hire Date: <input type="text" rv-value="model.hireDate" />
  <br/> 
  Phone: <input type="text" rv-value="model.phone" />
  <br/>
  <p>{model.name} was hired on {model.hireDate}</p>
  <br/> Division:
  <select id="SelectedDivision" name="SelectedDivision" rv-value="model.currentFilter">
    <option value=""></option>
    <option value="Roofing">Roofing</option>
    <option value="Siding">Siding</option>
    <option value="Stone">Stone</option>
  </select>
  <br/>

  <table class="table table-condensed table-bordered">
    <thead>
      <tr>
        <th class="col-sm-1">
          <input id="selectedAllBrands" type="checkbox" />
        </th>
        <th class="col-sm-11">Brand</th>
      </tr>
    </thead>
    <tbody rv-each-brand="model.brands | brandsFormatter model.brandFilter">
      <tr>
        <td>
          <input name="selectedBrands[]" type="checkbox" value="brand.name">
        </td>
        <td>{brand.name}</td>
      </tr>
    </tbody>
  </table>
</div>

JavaScript

var viewModel = {
  name: "Mindy Abair",
  phone: "480-502-7500",
  hireDate: "4/8/2005",
  brandFilter: "",
  brands: [{
    "name": "Atlantic Shutter",
    "owner": "Siding"
  }, {
    "name": "Builders Edge",
    "owner": "Siding"
  }, {
    "name": "Clubhouse",
    "owner": "Siding"
  }, {
    "name": "Dutch Quality",
    "owner": "Stone"
  }, {
    "name": "Eldorado Fireplaces",
    "owner": "Stone"
  }, {
    "name": "Eldorado Natural Stone",
    "owner": "Stone"
  }]
};

// add the brands filter
/*
rivets.formatters.brandsFormatter = function(brands, filter) {
		return $.grep(brands, function(brand) {
    		return filter.length > 0 ? brand.owner === filter : true;
  	});
};
*/
rivets.formatters.brandsFormatter = function(brands, filter) {
  return brands.filter(function(brand) {
    return filter.length > 0 ? brand.owner === filter : true;
  });
};

$(document).ready(function() {
  // wire up the division dropdown
  $("#SelectedDivision")
    .change(function() {
      viewModel.brandFilter = this.value;
      //selectAllBrands();
    });

  // data-binding
  rivets.bind(
    document.querySelector("#divBrands"), {
      model: viewModel
    }
  );
});