UNPKG

2.07 kBJavaScriptView Raw
1
2export function getActionObject(element) {
3 const action = element.getAttribute('action');
4 const parts = action.split('.');
5 const Model = parts[0];
6 let actionObject = null;
7 if (parts[1] === undefined) {
8 actionObject = window[Model];
9 } else {
10 const searchAction = parts[1];
11 try {
12 actionObject = window[Model][searchAction].bind(window[Model]);
13 } catch (e) {}
14 }
15
16 if (actionObject === undefined) {
17 throw new Error(`Bunny Error: Model search action specified in action="${action}" attribute not found`);
18 }
19 return actionObject;
20}
21
22export function initObjectExtensions(obj, arg) {
23 const keys = Object.keys(obj);
24 keys.forEach(key => {
25 if (key.indexOf('init') === 0) {
26 obj[key](arg);
27 }
28 });
29}
30
31export function pushToElementProperty(element, property, value) {
32 if (element[property] === undefined) {
33 element[property] = [];
34 }
35 element[property].push(value);
36}
37
38export function pushCallbackToElement(element, namespace, callback) {
39 pushToElementProperty(element, `__bunny_${namespace}_callbacks`, callback)
40}
41
42export function callElementCallbacks(element, namespace, cb) {
43 const callbacks = element[`__bunny_${namespace}_callbacks`];
44 if (callbacks !== undefined) {
45
46 // process each promise in direct order
47 // if promise returns false, do not execute further promises
48 const checkPromise = index => {
49 const res = cb(callbacks[index]); // actually calling callback
50 if (res instanceof Promise) {
51 res.then(cbRes => {
52 if (cbRes !== false) {
53 // keep going
54 if (index > 0) {
55 checkPromise(index-1);
56 }
57 }
58 })
59 } else {
60 if (res !== false) {
61 // keep going
62 if (index > 0) {
63 checkPromise(index-1);
64 }
65 }
66 }
67 };
68
69 checkPromise(callbacks.length - 1);
70 }
71}