我如何使用Backbone.Collection作为Backgrid.SelectCell的optionValues?

时间:2014-12-10 19:37:03

标签: backbone.js coffeescript backgrid

我有一个带有SprachLand模型的Backbone.Collection SprachLandList。

SprachLand

'use strict'
module.exports = class SprachLand extends Backbone.Model

SprachLandList

"use strict"
SprachLand = require('../models/SprachLand')
module.exports = class SprachLandList extends Backbone.Collection
model: SprachLand

我想用Backgrid显示另一个集合,这个集合有一个模型,其属性带有一个引用SprachLand模型的id数组。 现在我想将SprachlandList集合用于Backgrid中的Select2Cell单元格的值。 天真我试过

columns = [
  { name: "id", label: "ID", editable: false, cell: "integer" },
  { name: "bez", label: "Bezeichnung", editable: false, cell: "string" },
  { name: "rub.bez", label: "Rubrik", editable: false, cell: "string" },
  { name: "sl", label: "Sprachlandkombinationen", editable: true, cell:
      Backgrid.SelectCell.extend({
      #sllist is an instance of the SprachLandList
      optionValues: sllist 
      multiple: true
    })
}
]

我希望Select小部件显示" bez"属性"并拥有" id"属性为值。

这是sllist的JSON表示

"[{"id":1,"bez":"de-DE"},{"id":2,"bez":"fr-FR"},\ 
  {"id":3,"bez":"en-GB"},{"id":4,"bez":"nl-NL"},\ 
  {"id":5,"bez":"it-IT"},{"id":6,"bez":"de-CH"},\
  {"id":7,"bez":"fr-CH"},{"id":8,"bez":"it-CH"},\
  {"id":9,"bez":"de-AT"}]"

我收到错误:

Uncaught TypeError: 'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}

如何获得optionValues的SprachLandList集合的可接受表示?

1 个答案:

答案 0 :(得分:0)

经过一番搜索,我发现Converting Array of Objects into Array of Arrays

经过一些干预,我现在有了一个可能的解决方案:

columns = [
  { name: "id", label: "ID", editable: false, cell: "integer" },
  { name: "bez", label: "Bezeichnung", editable: false, cell: "string" },
  { name: "sl", label: "Sprachlandkombinationen", editable: true, cell: Backgrid.SelectCell.extend({
    optionValues: sllist.map((obj) ->
      nobj = obj.attributes
      Object.keys(nobj).sort().map (key) ->
        nobj[key]
    )
    formatter:
      fromRaw: (rawValue, model) ->
        (if _.isArray(rawValue) then rawValue else (if rawValue? then [rawValue] else []))
      toRaw: (formattedValue, model) ->
        (if not formattedValue? then [] else _.map(formattedValue, (v) ->             
          parseInt v
        ))
    multiple: true
    })
  }
  ]

格式化程序是在编辑后将select元素的字符串值转换回整数。

这是正确的解决方案吗?