Search code examples
javascriptjqueryrivets.js

Rivets.js rv-show not working with rv-each


I am new to Rivets.js. Given this code:

<div id="main">

  <div>
    <button rv-on-click="toggle">
      Toggle
    </button>
  </div>

  <div>
    Dynamic headers sould be visible: {showDynamicHeaders}
  </div>

  <table>
    <thead>
      <tr>
        <th>Fixed header</th>
        <th>Fixed header</th>
        <th rv-show="showDynamicHeaders" rv-each-item="items">
          {item.name}
        </th>
      </tr>
    </thead>
  </table>

</div>
var rvcontext = {};
var rview = rivets.bind($("#main"), rvcontext);  

rvcontext.showDynamicHeaders = true;

rvcontext.items = [
  {
    name : "Dynamic header 1"
  },{
    name : "Dynamic header 2"
  },{
    name : "Dynamic header 3"
  }
];

rvcontext.toggle = function(){
  rvcontext.showDynamicHeaders = !rvcontext.showDynamicHeaders;
}

I'd expect the table's dynamic headers to show up or not depending on the value of showDynamicHeaders. But it doesn't seem to work; instead, the headers are visible or not depending on the initial value of showDynamicHeaders, but their visibility doesn't change when the value is updated.

See this fiddle for a live example.

I am doing something wrong?


Solution

  • Try moving your rv-show to the <table> tag, like this:

    <table rv-show="showTable" >
        <tbody>
          <tr rv-each-item="items">
            <td>{item.name}</td>
          </tr>
        <tbody>
      </table>
    

    working fiddle

    Edit: Another option would be to add a rv-class tag in the each, like this:

     <div rv-each-i="data" rv-class-hide="i.a | neq 1">
        {i.a} - {i.b} ({i.c})
     </div>
    

    javascript:

    var data = [
        {a:1, b:"testing1", c:true},
        {a:1, b:"testing1a", c:true},
        {a:1, b:"testing1b", c:true},
        {a:2, b:"testing2", c:false},
        {a:2, b:"testing2a", c:true},
        {a:50, b:"testing50", c:false}
    ];
    
    rivets.formatters.neq = function(val, v2) { return val!=v2;};
    
    $(document).ready(function() {
        var $r = $('#rivets');
      rivets.bind($r, {data:data});
    });
    

    working fiddle of the rv-class method