Data binding and templating with Rivets

In my day job, I have been writing a lot of JavaScript.  The system already heavily uses jQuery and the addition of Angular would have been a tough sell.  I started to look for an alternative to handle data binding and templating.

My search led me to Rivets.js.  It is a very basic, lightweight (6.2kb) solution.  Let’s look at a few things that you can do with Rivets.

In the above example, we are doing a simple live html editor. There is a variable called items.content and it is bound to a textarea and a section.  It is bound to the textarea using the attribute ‘rv-value’ and it is bound to the section block using the attribute ‘rv-html’.  Notice that you need to actually create the binding using ‘rivets.bind()’.

In the above example, it is showing both the html and the output at the same time.  Using a little more Rivets magic, we can give the user the option of one or the other.

You will notice that there are two new attributes and two new buttons, above.  The two buttons are for “Show HTML” and “Show Output”.  When you click a button, it sets ‘items.showhtml’ or ‘items.showoutput’ to true and the other one to false.  Each button has ‘rv-disabled’ to disable it if has already been selected.  The section and textarea blocks have ‘rv-show’ attributes to toggle one or the other on, based upon the value of ‘items.showhtml’ and ‘items.showoutput’.

The important thing to remember is that the buttons do not directly affect the section and textarea blocks.  It is the binding of the element to the variables, that is driving everything.

1 thought on “Data binding and templating with Rivets

Leave a Reply

Your email address will not be published. Required fields are marked *