Knockout.Mapping和EcmaScript 5设置

时间:2012-12-12 17:45:12

标签: javascript knockout.js knockout-mapping-plugin ecmascript-5

ko.mapping可以在单个ko.computed中转换get, set property's (ES5)吗?

var people = { 
    get Name (){ 
        return this._name;
    },
    set Name(value){
        this._name = value;
    } 
};
var vm = ko.mapping(people, {/* mapping getset to computed */});
vm.Name instanceOf ko.computed === true.

ko.mapping支持这个或者怎么做?

1 个答案:

答案 0 :(得分:3)

我确定你的意思是使用一个可观察的,而不是一个计算的,因为这不依赖于其他的可观测量。

我创建了a gist, including tests,创建具有可观察属性的模型,以及一些用于创建它们的实用函数。核心代码在这里:

var defineProperty = function(type, obj, prop, def) {
  if (obj == null || typeof obj != 'object' || typeof prop != 'string') {
    throw new Error('invalid arguments passed');
  }

  if (Object.prototype.toString.call(def) === '[object Array]' && type === 'observable') {
    type = 'observableArray';
  }

  var obv = ko[type](def);
  Object.defineProperty(obj, prop, {
    set: function(value) { obv(value) },
    get: function() { return obv() },
    enumerable: true,
    configurable: true
  });

  Object.defineProperty(obj, '_' + prop, {
    get: function() { return obv },
    enumerable: false
  });
};

ko.utils.defineObservableProperty = defineProperty.bind(null, 'observable');
ko.utils.defineComputedProperty = defineProperty.bind(null, 'computed');

ko.observableModel = function(defaults) {
  for (var prop in defaults) {
    if (defaults.hasOwnProperty(prop)) {
      if (defaults[prop] != null && typeof defaults[prop] == 'object' && Object.prototype.toString.call(defaults[prop]) !== '[object Array]') {
        // should this also be an observable property?
        this[prop] = new ko.observableModel(defaults[prop]);
      } else if (!defaults[prop] || !ko.isSubscribable(defaults[prop])) {
        ko.utils.defineObservableProperty(this, prop, defaults[prop]);
      } else {
        this[prop] = defaults[prop];
      }
    }
  }
};