Rivets 101: Showing and hiding elements

In our previous riveting Rivets.js post, we revisited data binding and templating.  In addition to that, Rivets can handle showing and hiding elements within the DOM.  Within this post, we are going to a single-page application by selectively hiding and showing elements.

Our first example does not execute properly on JSFiddle but you can run it off of steinbring.net.

In the above example, there are three buttons connected to three divs.  Each button changes the value of the variable ‘items.selected’.  The content divs then use the ‘rv-show’ attribute to show and hide the divs based upon the value of ‘items.selected’.  The problem is that this kind of comparison does not work out of the box.  You need to create a formatter in order to do it.  In the example, I created ‘rivets.formatters.eq’ but you can also create ‘rivets.formatters.neq’, ‘rivets.formatters.gt’, or ‘rivets.formatters.lt’ just as easy.  Since you are defining the formatter, you can call it whatever you want, as well.

The problem with our first example is that there is no mechanism for storage of a selection.  It is useful to give the user the ability to toggle tabs on and off but it would be nice to be able to link to tabs.

You will notice that our second example uses hrefs instead of buttons.  The links are pointing to divs on the same page.  I then created a function called ‘hashHandler’, which looks for changes in the value of ‘window.location.hash’ once every 100 milliseconds.  If the hash in the URL changes, it changes the value of ‘items.selected’.  That value is then bound in the same way that it is bound in the first example.

Have any questions?  Feel free to drop a comment below or shoot me a message.

Leave a Reply

Your email address will not be published.