Best way to bind data to an onchange of a select element using rivets

1.3k Views Asked by At

I have a page with an array with some books titles and prices, and I populated a select with the books titles. I am using rivets to select items and show the selected items below.

My dropdown select list is working. But it does not show the selected item below the dropdown list OR said in other words I want to bind the onchange event of the select to the current item on the array.

Is that possible? If so how?

I searched the internet but there is almost no resources for learning rivets. This is my code:

<!DOCTYPE HTML>
<html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <title>Rivets test</title>
        <script src="../js/rivets.js"></script>
    </head>
    <body>

        <h3>Livros no saraiva.com.br</h3>

        <select id="select">
            <option rv-each-book="books">{book.title}</option>
        </select>

        <br><br>

        <div id="contents">
            <strong>Título:</strong> <span>{book.title}</span><br>
            <strong>Valor:</strong> <span>{book.price}</span>
        </div>

        <script>

        var s = document.getElementById('select'),
            books = [
            {
                "title": "Como treinar o seu dragão",
                "price": 29.90
            },
            {
                "title": "Livro de colorir mangá",
                "price": 17.40
            },
            {
                "title": "Heróis para colorir",
                "price": 27.90
            },
            {
                "title": "O pequeno príncipe",
                "price": 17.70
            },
            {
                "title": "Guerra civil",
                "price": 21.70
            }
        ];

        rivets.bind(s, {"books": books});

        </script>

    </body>
</html>

What would be the best way to bind the onchange to the view using rivets?

2

There are 2 best solutions below

2
On

you have to use some of the Rivets events handlers, for example:

<button rv-on-click="clickHandler">Remove</button>

Then you need to have a method in your model called clickHandler, like this:

var model = {
items: [1,2,3,4,5],
clickHandler: function(e){
    //handler code
}

};

Here's a blog post using different Rivets features (in spanish but you will understand the code samples).

http://www.leomicheloni.com/post/2014/04/26/Automatic-html-binding-con-Rivetsjs.aspx

Hope it helps.

0
On

you can add rv-value to the select tag and to the options tag , because the literals only displays the value from the model property ,as below :

<select  rv-value="data.selectedBook">
  <option rv-each-book="books" rv-value="book.title">{ book.title }</option>
</select>

//and display the binded value as following:
 <strong>Título:</strong> <span>{data.selectedBook}</span>

I hope it helps!