UNPKG

2.75 kBJavaScriptView Raw
1/*
2Copyright 2013-2015 ASIAL CORPORATION
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15
16*/
17import util from './util.js';
18import internal from './internal/index.js';
19
20// Default implementation for global PageLoader.
21function loadPage({page, parent, params = {}}, done, error) {
22 internal.getPageHTMLAsync(page).then(html => {
23 const pageElement = util.createElement(html);
24 parent.appendChild(pageElement);
25
26 done(pageElement);
27 }).catch(e => error(e));
28}
29
30function unloadPage(element) {
31 if (element._destroy instanceof Function) {
32 element._destroy();
33 } else {
34 element.remove();
35 }
36}
37
38export class PageLoader {
39 /**
40 * @param {Function} [fn] Returns an object that has "element" property and "unload" function.
41 */
42 constructor(loader, unloader) {
43 this._loader = loader instanceof Function ? loader : loadPage;
44 this._unloader = unloader instanceof Function ? unloader : unloadPage;
45 }
46
47 /**
48 * Set internal loader implementation.
49 */
50 set internalLoader(fn) {
51 if (!(fn instanceof Function)) {
52 throw Error('First parameter must be an instance of Function');
53 }
54 this._loader = fn;
55 }
56
57 get internalLoader() {
58 return this._loader;
59 }
60
61 /**
62 * @param {any} options.page
63 * @param {Element} options.parent A location to load page.
64 * @param {Object} [options.params] Extra parameters for ons-page.
65 * @param {Function} done Take an object that has "element" property and "unload" function.
66 * @param {Function} error Function called when there is an error.
67 */
68 load({page, parent, params = {}}, done, error) {
69 this._loader({page, parent, params}, pageElement => {
70 if (!(pageElement instanceof Element)) {
71 throw Error('pageElement must be an instance of Element.');
72 }
73
74 done(pageElement);
75 }, error);
76 }
77
78 unload(pageElement) {
79 if (!(pageElement instanceof Element)) {
80 throw Error('pageElement must be an instance of Element.');
81 }
82
83 this._unloader(pageElement);
84 }
85}
86
87export const defaultPageLoader = new PageLoader();
88
89export const instantPageLoader = new PageLoader(
90 function({page, parent, params = {}}, done) {
91 const element = util.createElement(page.trim());
92 parent.appendChild(element);
93
94 done(element);
95 },
96 unloadPage
97);