Iterating over javascript objects with handlebars

风流意气都作罢 提交于 2019-12-06 01:56:17

Your JavaScript to CoffeeScript transliteration is broken. You don't use for ... in to iterate over an object in CoffeeScript, you use for k, v of ...:

Use of to signal comprehension over the properties of an object instead of the values in an array.

This CoffeeScript loop:

for x in y
    ...

becomes this JavaScript:

for (_i = 0, _len = y.length; _i < _len; _i++) {
  x = a[_i];
  ...
}

So if y is an object without a length property, then _len will be undefined and the JavaScript for(;;) loop won't iterate at all.

You should also be using own instead of hasOwnProperty:

If you would like to iterate over just the keys that are defined on the object itself, by adding a hasOwnProperty check to avoid properties that may be interited from the prototype, use for own key, value of object.

but that's more for convenience than correctness.

Also, CoffeeScript loops are expressions so you'd usually say array = expr for own k, v in o or the equivalent form:

array = for own k, v in o
    expr

if expr is more than one line or too long to allow for a readable comprehension.

A correct and more idiomatic version of your helpers in CoffeeScript would look more like this:

Handlebars.registerHelper "key_value", (obj, fn)->
    (fn(key: key, value: value) for own key, value of obj).join('')

Handlebars.registerHelper "each_with_key", (obj, fn)->
    key_name = fn.hash.key
    buffer   = for own key, value of obj
        value[key_name] = key
        fn(value)
    buffer.join('')

Demo: http://jsfiddle.net/ambiguous/LWTPv/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!