在EmberJS模型中,有没有更好的方法来解析和绑定到json对象作为属性?

时间:2013-10-28 19:42:20

标签: javascript ember.js coffeescript ember-data

这是用于解析和绑定json对象作为属性(也有一个转换,但它是非常基本的):

cleanCredentials: ->
  creds = @get('credentials')
  Object.keys(creds).forEach (key) =>
    unless key in @get('selectedDriver').api_keys
      delete @get('credentials')["#{key}"]

get_set: ->
  key   = arguments[0][0]
  value = arguments[0][1]
  if (arguments[0].length > 1)
    @set "credentials.#{key}", value
    @cleanCredentials()
  @get "credentials.#{key}"

getter_setter = `function(key, value) { return this.get_set(arguments); }.property('credentials')`

apiToken:          getter_setter
applicationId:     getter_setter
applicationUserId: getter_setter
companyCode:       getter_setter
username:          getter_setter

它有效,我明白了,但有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

IIUC,您应该定义自定义转换:

App.RawTransform = DS.Transform.extend({
  deserialize: function(json) {
    return json;
  },
  serialize: function(object) {
    return object;
  }
});

App.Model = DS.Model.extend({
  rawJSONobject: DS.attr('raw')
});

答案 1 :(得分:0)

此解决方案将无法绑定到json字符串中的各个项目,但会查看整个json字符串...此外,还无法对此进行测试,但希望这会给您一些想法。< / p>

App.Person = Ember.Model.extend({

  // json string
  'jsonData' : DS.attr('string'),

  // computed property
  'parsedData' : function(key, value) {

      // setter -- take an object and save the stringified version to the model
      if (arguments.length > 1) {
          this.set('jsonData', JSON.stringify(value));
      }

      // return the parsed json string rather than the string itself...
      return $.parseJSON(this.get('jsonData'));

  }.property('jsonData')

});