Search code examples
javascripthtmlarraystemplatingrivets.js

Accessing array index with Rivets.js


I am wondering why accessing an index of an array bound in rivets.js works with the . operator and not the standard access way with [].

For example

let's say we bind

var binding = {name: "binding", arr: [0,1,2]}
rivets.bind(document, {binding: binding});

then in our html if we do, it won't work

<span> {binding.arr[0]}</span>

but if we do

 <span> {binding.arr.0}</span>

The 0th element of the array is successfully accessed.

Where in rivets is this behavior documented? Is this the standard way to access array elements in templating engines? I wasn't able to find it anywhere and it's really bothering me.


Solution

  • <span> {binding.arr.0}</span> works because Arrays are objects. So it works the same way other objects do with the . operator (returns obj[key]).

    Ideally while working with arrays you should be using rv-each.

    for some reason if you have to access item at specific index and is unconfortable about <span> {binding.arr.0}</span> looks confusing or unreadable, I suggest creating a formatter along the lines of:

    rivets.formatters.itemat = function(value,index){
      if(!(value && value instanceof Array))
        return null; // throw some error if required
      return value[index || 0];
    }
    

    which can be used like

    <span> {binding.arr | itemat 0}</span>