rivets icon indicating copy to clipboard operation
rivets copied to clipboard

iterate over objects

Open matthewmueller opened this issue 11 years ago • 6 comments

It's sometimes useful to iterate over objects and it looks like data-each-obj doesn't support that.

matthewmueller avatar Dec 06 '12 03:12 matthewmueller

Would you just want to iterate values of an object?

yocontra avatar Dec 06 '12 15:12 yocontra

The each-[item] binder is really just for arrays. People try to use it with other objects such as Backbone Collections and wonder why it's not working — for these situations, writing your own custom binder is really the best way to go.


What confuses me a bit though, is that you're saying "iterate over objects" and data-each-obj hints that you want each iteration to be an "object". If this is actually what you want, then just put those objects in an array and it should work?

If you meant "iterate over an object's properties" than that is a different story and would probably look more like data-each-[key]-[value] where each iteration would have both a key and a value context.

If you don't need to bind to properties on the iterated values, then you can get around this by using a formatter to turn your object into an array of key/value pairs. This actually works really well if you're just using the object as an associative array and need to loop over it.

rivets.formatters.propertyList = (obj) ->
  ({key: key, value: value} for key, value of obj)
<ul>
  <li data-each-property="some.object | propertyList">
    <strong data-text="property.key"></strong>: <span data-text="property.value"></span>
  </li>
</ul>

Here is a fiddle to demonstrate how this formatter approach works.

mikeric avatar Dec 18 '12 01:12 mikeric

I think data-each-[key]-[value] has a nice purpose though too ^

yocontra avatar Dec 18 '12 03:12 yocontra

:+1: for data-each-[key]-[value]

woozyking avatar Nov 19 '14 22:11 woozyking

Just thinking aloud here, in case we get around to giving this a shot – the problem I foresee is how to watch for additions/deletions of properties. The rv-each binder watches for new or removed array items by stubbing the array methods (push(), pop(), splice() etc.).

However, using es6, we could use a setter with a computed property name to watch for new properties. Not sure how we can watch for removal of properties, although perhaps that case is so rare that we don't need to worry about that.

benadamstyles avatar Jan 27 '16 11:01 benadamstyles

If RivetJS doesn't support expressing basic javascript concepts, whats really the point?

  ({key: key, value: value} for key, value of obj)

<ul>
  <li data-each-property="some.object | propertyList">
    <strong data-text="property.key"></strong>: <span data-text="property.value"></span>
  </li>
</ul>````

this doesnt support two way databinding because your changing the reference

numlck avatar Apr 10 '20 15:04 numlck