UNPKG

2.12 kBJavaScriptView Raw
1import Observer from './observer.js';
2import Binder from './binder.js';
3
4export default {
5
6 GET: 2,
7 SET: 3,
8 REMOVE: 4,
9 data: null,
10 tasks: [],
11 target: {},
12
13 async setup (options) {
14 options = options || {};
15 this.target = options.target || this.target;
16 this.data = Observer.create(this.target, this.listener.bind(this));
17 },
18
19 traverse (type, keys, value) {
20 let result;
21
22 if (typeof keys === 'string') {
23 keys = keys.split('.');
24 }
25
26 let data = this.data;
27 let key = keys[keys.length-1];
28
29 for (let i = 0, l = keys.length-1; i < l; i++) {
30
31 if (!(keys[i] in data)) {
32
33 if (type === this.GET || type === this.REMOVE) {
34 return undefined;
35 } else if (type === this.SET) {
36 data.$set(keys[i], isNaN(keys[i+1]) ? {} : []);
37 }
38
39 }
40
41 data = data[keys[i]];
42 }
43
44 if (type === this.SET) {
45 result = data.$set(key, value);
46 } else if (type === this.GET) {
47 result = data[key];
48 } else if (type === this.REMOVE) {
49 result = data[key];
50 data.$remove(key);
51 }
52
53 return result;
54 },
55
56 get (keys) {
57 return this.traverse(this.GET, keys);
58 },
59
60 remove (keys) {
61 return this.traverse(this.REMOVE, keys);
62 },
63
64 set (keys, value) {
65 return this.traverse(this.SET, keys, value);
66 },
67
68 listener (data, location, type) {
69 const parts = location.split('.');
70 const part = parts.slice(1).join('.');
71 const scope = parts.slice(0, 1).join('.');
72
73 const paths = Binder.get('location', scope);
74
75 if (!paths) return;
76
77 paths.forEach(function (binders, path) {
78 if (
79 part === '' ||
80 path === part ||
81 (type !== 'length' && path.indexOf(part + '.') === 0)
82 ) {
83 binders.forEach(function (binder) {
84 Binder.render(binder);
85 });
86 }
87 });
88
89 }
90
91};