Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data binding in rivets js

Tags:

rivets.js

I came across rivets library and tried to do simple example. But I had 2 issues:

  1. In tutorial they write "user.name" (with dot) but for me it works only if I write "user:name"
  2. When I change the user.name property why DOM doesn't change?

The code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />

    <title>Example</title>

    <script src="/js/rivets.min.js"></script>
    <script src="/js/jquery-2.0.0.min.js"></script>
    <script>
        $(function() {
            var user = {
                name: 'User'
            }

            $('#userName').keyup(function() { 
                user.name = $('#userName').val();
            });

            rivets.bind($('#user'), { user:user })
        });
    </script>
</head>

<body>
    <input type="text" id="userName" />

    <div id="user">
        <p data-text="user:name"></p>
    </div>
</body>
</html>
like image 324
Victor Avatar asked Jul 09 '26 17:07

Victor


1 Answers

Disclaimer : This answer was written for Rivets.js < 0.5. If you're using 0.6 or greater, please see the current documentation for adapters instead.

http://rivetsjs.com/#adapters


The . notation uses the adapter to subscribe to the model for changes on a particular attribute. Since you haven't specified an adapter, Rivets.js doesn't know how to read or subscribe to the model for changes. See http://rivetsjs.com/#configure.

The : notation bypasses the adapter and reads the property directly on the model. This is a read-only operation and doesn't perform any further data binding. Without defining an adapter, this is really all you can do and doesn't provide much benefit over static templating unless paired with dependencies or is in the context of an iteration (an adapter is needed to do either of those).

You don't mention any framework or events library that you're using, and from your example you are trying to bind to a plain JavaScript object. Typically, Rivets.js is used alongside another library that provides change events for your models such as Backbone.js or Iota Observable. This is because current browsers don't have the ability to observe plain JavaScript objects for changes... yet... (See Object.observe proposal).

I'd recommend using one of those libraries alongside Rivets.js, but if you're totally set on using plain JavaScript objects, you can look at using something like Watch.js or an Object.observe shim. Either way, you need to define an adapter.

like image 65
Michael Richards Avatar answered Jul 11 '26 12:07

Michael Richards