简体   繁体   中英

Detecting changes to arrays with RivetsJS

I'm a new user of RivetsJS and am trying to figure out how to get my bindings to refresh when array elements are modified . It seems like Rivets is able to detect changes to non-complex variables when simple assignments are used (ie player_lives -= 1 ). It also detects when I push() to a bound array. No refresh occurs when I assign a new value to an existing array element, though. Here's an example of what I'm trying:

<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/rivets/0.8.1/rivets.bundled.min.js"></script>
    <script type="text/javascript">
        var numbers = [111, 222, 333];

        window.addEventListener('load', function() {
            rivets.bind(document.getElementById('numbers'), {numbers: numbers});
        });

        function changeNum() {
            numbers[0] = 5;
        }
    </script>
</head>
<body>
    <button onclick="changeNum()">Add a number</button>
    <div id="numbers">{ numbers }</div>
</body>
</html>

In this case the { numbers } binding is not refreshed and the original values continue to display. I suspect that Rivets isn't able to detect that the change is occurring, but I'm not sure what the best approach to take to remedy that would be. Any suggestions?

It seems rivets can't detect the changes to indexes of an array.

However, it does detect when the reference to array changes.

So one solution is to trigger a reference change, in your example, something like

function changeNum() {
  //numbers[0] = 5;
  numbers = [5].concat(numbers.slice(1)); // [5, 222, 333]
}

Will trigger an update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM