Merge pull request #54 from ihadeed/add-event-wrapper

Add event wrapper
This commit is contained in:
Ibrahim Hadeed 2016-03-14 13:25:00 -04:00
commit 06749ea211

View File

@ -141,6 +141,19 @@ function wrapObservable(pluginObj:any, methodName:string, args:any[], opts:any =
}); });
} }
/**
* Wrap the event with an observable
* @param event
* @returns {Observable}
*/
function wrapEventObservable (event : string) : Observable<any> {
return new Observable(observer => {
let callback = (status : any) => observer.next(status);
window.addEventListener(event, callback, false);
return () => window.removeEventListener(event, callback, false);
});
}
/** /**
* @private * @private
* @param pluginObj * @param pluginObj
@ -151,13 +164,17 @@ function wrapObservable(pluginObj:any, methodName:string, args:any[], opts:any =
export const wrap = function(pluginObj:any, methodName:string, opts:any = {}) { export const wrap = function(pluginObj:any, methodName:string, opts:any = {}) {
return (...args) => { return (...args) => {
if (opts.sync){ if (opts.sync)
return callCordovaPlugin(pluginObj, methodName, args, opts); return callCordovaPlugin(pluginObj, methodName, args, opts);
} else if (opts.observable) {
else if (opts.observable)
return wrapObservable(pluginObj, methodName, args, opts); return wrapObservable(pluginObj, methodName, args, opts);
} else {
else if (opts.eventObservable && opts.event)
return wrapEventObservable(opts.event);
else
return wrapPromise(pluginObj, methodName, args, opts); return wrapPromise(pluginObj, methodName, args, opts);
}
} }
}; };