在构造函数coffeescript中打印出数组

时间:2013-05-11 20:38:33

标签: coffeescript

这应该打印出集合中的所有内容 但它只打印出两个元素。

为什么不打印整个列表? 这是某种种族案件吗?

http://jsfiddle.net/Czenu/1/

class window.Restful
  constructor:->
    _.each @collection, (action,kind)=>
      $('.actions').append "<div>#{action} #{kind}</div>"

class Material extends Restful
  namespace:  'admin/api'
  table_name: 'materials'
  constructor:(@$rootScope,@$http)->
    super
  collection:
    get: 'downloaded'
    get: 'incomplete'
    get: 'submitted'
    get: 'marked'
    get: 'reviewed'
    get: 'corrected'
    get: 'completed'
    post: 'sort'
    post: 'sort_recieve'

new Material()

1 个答案:

答案 0 :(得分:2)

您的collection对象包含只有两个不同键的元素:“get”和“post”。由于每个键只能映射到一个值,因此您的对象将缩减为:

  collection:
    get: 'downloaded'
    ...
    get: 'corrected'
    get: 'completed'
    post: 'sort'
    post: 'sort_recieve'

解决方案是制作更有意义的对象,例如自定义对象数组(使用具有有意义名称的快捷方式函数创建,如下例所示。)。

class window.Restful
  constructor: ->
    _.each @collection, (obj) =>
      {action,kind} = obj
      $('.actions').append "<div>#{action} #{kind}</div>"

class Material extends Restful
  get = (action) -> {action, kind:'get'}
  post = (action) -> {action, kind:'post'}
  ...

  collection: [
    get 'downloaded'
    get 'incomplete'
    get 'submitted'
    get 'marked'
    get 'reviewed'
    get 'corrected'
    get 'completed'
    post 'sort'
    post 'sort_recieve'
  ]

完整结果显示在http://jsfiddle.net/Czenu/2/