JavaScript代理的替代品

时间:2016-06-01 03:56:07

标签: javascript ecmascript-6 observer-pattern es6-proxy

我想在名为Proxy的自定义类中使用ObservableList,该类包含Array。由于Proxy仅在ES6之后可用,我想知道是否有任何替代实现。

我的要求是在ObservableList更改后对观察者进行更新(而不是引起注意),以便观察者总是使用一些过滤或映射方法与observable一起构成。

var activities = new ObservableList(['reading', 'swimming']);
var sAct = activities.filter(function(v) {
  return v[0] === 's';
});
// expect sAct.list to be ['swimming']
var meAct = activities.map(function(v) {
  return 'I am ' + v;
});
// expect meAct.list to be ['I am reading', 'I am swimming']

activities.list.push('smiling');
console.log(sAct.list, meAct.list);
// expect sAct.list to be ['swimming', 'smiling']
// expect meAct.list to be ['I am reading', 'I am swimming', 'I am smiling']

activities.list[1] = 'snoopying';
console.log(sAct.list, meAct.list);
// expect sAct.list to be ['swimming', 'snoopying']
// expect meAct.list to be ['I am reading', 'I am snoopying', 'I am smiling']

我在https://jsfiddle.net/ovilia/tLmbptr0/3/

上可以使用代理实现

3 个答案:

答案 0 :(得分:2)

使用defineProperty

不完全符合你的要求。我刚刚实现了一个"反应阵列"。但我认为它可能适用于你的问题。

坏的部分:

  1. 在目标上定义了大量的getter / setter。
  2. 访问未定义的索引器将不会被动。
  3. update()将进行优化。
  4. 好的部分:

    1. ES5友好。
    2. 如果不需要索引器,则使用set(i, val)/get(i)将被激活。
    3. https://jsfiddle.net/jimnox/jrtq40p7/2/

答案 1 :(得分:0)

使用代理是一项艰难的要求吗?我不推荐代理 一般的编程任务,因为你最终可能会出现不可预测的问题 难以发现的副作用。

如果你继续使用数据和函数来转换它,那就避免变异了 在可能的情况下,我认为你最终会得到更简单的代码 更容易维护。



var activities = ['reading', 'swimming'];

var sfilter = function(activities){
    return activities.filter(function(v){
        return v[0] === 's';
    });
};

console.log(sfilter(activities));

var memap = function(activities){
    return activities.map(function(v){
        return 'I am ' + v;
    });
};

console.log(memap(activities));

activities.push('smiling');
console.log(sfilter(activities));
console.log(memap(activities));

// Yes, I know this doesn't work in quite the same way,
// but you're asking for trouble here since in your
// code you're appending to one list, but overwriting
// an element in the other.
activities[1] = 'snoopying';
console.log(sfilter(activities));
console.log(memap(activities));




坚持单一的真理来源并观察它。每个副本都会增加状态复杂性。这将使调试,测试和扩展代码变得困难。

答案 2 :(得分:0)

如问题中所述,我只需要ObservableList 包含 Array,而不是扩展,就像Jim在他的复杂的答案。令人惊讶的是,我发现通过包装原始Array操作可以轻松实现

一个限制是在我的实现中索引操作不是被动的,因为我找不到捕获索引操作的正确方法。如果你有更好的主意,欢迎告诉我! XD

这是完整的实施。

export class ObservableList {

  list: Array<any>;

  private _observer: Array<ObserverList>;

  constructor(list?: Array<any>) {
    this.list = list || [];
    this._initList();
    this._initMethods();

    this._observer = [];
  }

  notify(): void {
    for (let o of this._observer) {
      o.update();
    }
  }

  private _initList(): void {
    var that = this;
    var operations = ['push', 'pop', 'shift', 'unshift', 'splice',
      'sort', 'reverse'];
    for (let operation of operations) {
      this.list[operation] = function() {
        var res = Array.prototype[operation].apply(that.list, arguments);
        that.notify();
        return res;
      }
    }
  }

  private _initMethods(): void {
    var that = this;
    var methods = ['filter', 'map'];
    for (let method of methods) {
      this[method] = (formatter: Function): ObserverList => {
        var observer = new ObserverList(that, formatter, method);
        this._observer.push(observer);
        return observer;
      }
    }
  }

}

export class ObserverList {

  public list: Array<any>;

  constructor(public observable: ObservableList, 
              public formatter: Function, 
              public method: string) {
    this.list = [];
    this.update();
  }

  update(): void {
    var list = [];
    var master = this.observable.list;
    for (var i = 0, len = master.length; i < len; ++i) {
      if (this.method === 'filter') {
        if (this.formatter(master[i])) {
          list.push(master[i]);
        }
      } else if (this.method === 'map') {
        list.push(this.formatter(master[i]));
      } else {
        console.error('Illegal method ' + this.method + '.');
      }
    }
    this.list = list;
  }

}