Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives of JavaScript Proxy

I want to use Proxy on a customized class called ObservableList which contains an Array. Since Proxy is available only after ES6, I wonder if there is any alternative implementation.

My requirement is to get updated (rather than get noticed) for observers once ObservableList changes, so that the observers are always consist with observable with some filtering or mapping method.

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']

My implementation with Proxy is available at https://jsfiddle.net/ovilia/tLmbptr0/3/

like image 723
Ovilia Avatar asked Jun 01 '16 03:06

Ovilia


1 Answers

used defineProperty.

not exactly with what you want. i just implemented a "reactive array". but i think it maybe works in your problems.

bad parts:

  1. defined tons of getters/setters on the target.
  2. accessing indexers not defined will be not reactive.
  3. update() is to-be optimized.

good parts:

  1. ES5 friendly.
  2. if no indexers needed, use set(i, val)/get(i) will be reactive.

https://jsfiddle.net/jimnox/jrtq40p7/2/

like image 117
LiuJi-Jim Avatar answered Oct 16 '22 14:10

LiuJi-Jim