Debian Codegraph @

dojox/app/main.js

raw symbols SCIP
1 define(["require", "dojo/_base/kernel", "dojo/_base/lang", "dojo/_base/declare", "dojo/_base/config",
2 "dojo/_base/window", "dojo/Evented", "dojo/Deferred", "dojo/when", "dojo/has", "dojo/on", "dojo/ready",
3 "dojo/dom-construct", "dojo/dom-attr", "./utils/model", "./utils/nls", "./module/lifecycle",
4 "./utils/hash", "./utils/constraints", "./utils/config"],
5 function(require, kernel, lang, declare, config, win, Evented, Deferred, when, has, on, ready, domConstruct, domAttr,
6 model, nls, lifecycle, hash, constraints, configUtils){
7
8 has.add("app-log-api", (config["app"] || {}).debugApp);
9
10 var Application = declare(Evented, {
11 constructor: function(params, node){
12 declare.safeMixin(this, params);
13 this.params = params;
14 this.id = params.id;
15 this.defaultView = params.defaultView;
16 this.controllers = [];
17 this.children = {};
18 this.loadedModels = {};
19 this.loadedStores = {};
20 // Create a new domNode and append to body
21 // Need to bind startTransition event on application domNode,
22 // Because dojox/mobile/ViewController bind startTransition event on document.body
23 // Make application's root domNode id unique because this id can be visited by window namespace on Chrome 18.
24 this.setDomNode(domConstruct.create("div", {
25 id: this.id+"_Root",
26 style: "width:100%; height:100%; overflow-y:hidden; overflow-x:hidden;"
27 }));
28 node.appendChild(this.domNode);
29 },
30
31 createDataStore: function(params){
32 // summary:
33 // Create data store instance
34 //
35 // params: Object
36 // data stores configuration.
37
38 if(params.stores){
39 //create stores in the configuration.
40 for(var item in params.stores){
41 if(item.charAt(0) !== "_"){//skip the private properties
42 var type = params.stores[item].type ? params.stores[item].type : "dojo/store/Memory";
43 var config = {};
44 if(params.stores[item].params){
45 lang.mixin(config, params.stores[item].params);
46 }
47 // we assume the store is here through dependencies
48 try{
49 var storeCtor = require(type);
50 }catch(e){
51 throw new Error(type+" must be listed in the dependencies");
52 }
53 if(config.data && lang.isString(config.data)){
54 //get the object specified by string value of data property
55 //cannot assign object literal or reference to data property
56 //because json.ref will generate __parent to point to its parent
57 //and will cause infinitive loop when creating StatefulModel.
58 config.data = lang.getObject(config.data);
59 }
60 if(params.stores[item].observable){
61 try{
62 var observableCtor = require("dojo/store/Observable");
63 }catch(e){
64 throw new Error("dojo/store/Observable must be listed in the dependencies");
65 }
66 params.stores[item].store = observableCtor(new storeCtor(config));
67 }else{
68 params.stores[item].store = new storeCtor(config);
69 }
70 this.loadedStores[item] = params.stores[item].store;
71 }
72 }
73 }
74 },
75
76 createControllers: function(controllers){
77 // summary:
78 // Create controller instance
79 //
80 // controllers: Array
81 // controller configuration array.
82 // returns:
83 // controllerDeferred object
84
85 if(controllers){
86 var requireItems = [];
87 for(var i = 0; i < controllers.length; i++){
88 requireItems.push(controllers[i]);
89 }
90
91 var def = new Deferred();
92 var requireSignal;
93 try{
94 requireSignal = require.on ? require.on("error", function(error){
95 if(def.isResolved() || def.isRejected()){
96 return;
97 }
98 def.reject("load controllers error.");
99 if(requireSignal){
100 requireSignal.remove();
101 }
102 }) : null;
103 require(requireItems, function(){
104 def.resolve.call(def, arguments);
105 if(requireSignal){
106 requireSignal.remove();
107 }
108 });
109 }catch(e){
110 def.reject(e);
111 if(requireSignal){
112 requireSignal.remove();
113 }
114 }
115
116 var controllerDef = new Deferred();
117 when(def, lang.hitch(this, function(){
118 for(var i = 0; i < arguments[0].length; i++){
119 // instantiate controllers, set Application object, and perform auto binding
120 this.controllers.push((new arguments[0][i](this)).bind());
121 }
122 controllerDef.resolve(this);
123 }), function(){
124 //require def error, reject loadChildDeferred
125 controllerDef.reject("load controllers error.");
126 });
127 return controllerDef;
128 }
129 },
130
131 trigger: function(event, params){
132 // summary:
133 // trigger an event. Deprecated, use emit instead.
134 //
135 // event: String
136 // event name. The event is binded by controller.bind() method.
137 // params: Object
138 // event params.
139 kernel.deprecated("dojox.app.Application.trigger", "Use dojox.app.Application.emit instead", "2.0");
140 this.emit(event, params);
141 },
142
143 // setup default view and Controllers and startup the default view
144 start: function(){
145 //
146 //create application level data store
147 this.createDataStore(this.params);
148
149 // create application level data model
150 var loadModelLoaderDeferred = new Deferred();
151 var createPromise;
152 try{
153 createPromise = model(this.params.models, this, this);
154 }catch(e){
155 loadModelLoaderDeferred.reject(e);
156 return loadModelLoaderDeferred.promise;
157 }
158 when(createPromise, lang.hitch(this, function(models){
159 // if models is an array it comes from dojo/promise/all. Each array slot contains the same result object
160 // so pick slot 0.
161 this.loadedModels = lang.isArray(models)?models[0]:models;
162 this.setupControllers();
163 // if available load root NLS
164 when(nls(this.params), lang.hitch(this, function(nls){
165 if(nls){
166 lang.mixin(this.nls = {}, nls);
167 }
168 this.startup();
169 }));
170 }), function(){
171 loadModelLoaderDeferred.reject("load model error.")
172 });
173 },
174
175 setDomNode: function(domNode){
176 var oldNode = this.domNode;
177 this.domNode = domNode;
178 this.emit("app-domNode", {
179 oldNode: oldNode,
180 newNode: domNode
181 });
182 },
183
184 setupControllers: function(){
185 // create application controller instance
186 // move set _startView operation from history module to application
187 var currentHash = window.location.hash;
188 // this._startView = (((currentHash && currentHash.charAt(0) == "#") ? currentHash.substr(1) : currentHash) || this.defaultView).split('&')[0];
189 this._startView = hash.getTarget(currentHash, this.defaultView);
190 this._startParams = hash.getParams(currentHash);
191 },
192
193 startup: function(){
194 // load controllers and views
195 //
196 this.selectedChildren = {};
197 var controllers = this.createControllers(this.params.controllers);
198 // constraint on app
199 if(this.hasOwnProperty("constraint")){
200 constraints.register(this.params.constraints);
201 }else{
202 this.constraint = "center";
203 }
204 var emitLoad = function(){
205 // emit "app-load" event and let controller to load view.
206 this.emit("app-load", {
207 viewId: this.defaultView,
208 initLoad: true,
209 params: this._startParams,
210 callback: lang.hitch(this, function (){
211 this.emit("app-transition", {
212 viewId: this.defaultView,
213 forceTransitionNone: true, // we want to avoid the transition on the first display for the defaultView
214 opts: { params: this._startParams }
215 });
216 if(this.defaultView !== this._startView){
217 // transition to startView. If startView==defaultView, that means initial the default view.
218 this.emit("app-transition", {
219 viewId: this._startView,
220 opts: { params: this._startParams }
221 });
222 }
223 this.setStatus(this.lifecycle.STARTED);
224 })
225 });
226 };
227 when(controllers, lang.hitch(this, function(){
228 if(this.template){
229 // emit "app-init" event so that the Load controller can initialize root view
230 this.emit("app-init", {
231 app: this, // pass the app into the View so it can have easy access to app
232 name: this.name,
233 type: this.type,
234 parent: this,
235 templateString: this.templateString,
236 controller: this.controller,
237 callback: lang.hitch(this, function(view){
238 this.setDomNode(view.domNode);
239 emitLoad.call(this);
240 })
241 });
242 }else{
243 emitLoad.call(this);
244 }
245 }));
246 }
247 });
248
249 function generateApp(config, node){
250 // summary:
251 // generate the application
252 //
253 // config: Object
254 // app config
255 // node: domNode
256 // domNode.
257 var path;
258
259 // call configProcessHas to process any has blocks in the config
260 config = configUtils.configProcessHas(config);
261
262 if(!config.loaderConfig){
263 config.loaderConfig = {};
264 }
265 if(!config.loaderConfig.paths){
266 config.loaderConfig.paths = {};
267 }
268 if(!config.loaderConfig.paths["app"]){
269 // Register application module path
270 path = window.location.pathname;
271 if(path.charAt(path.length) != "/"){
272 path = path.split("/");
273 path.pop();
274 path = path.join("/");
275 }
276 config.loaderConfig.paths["app"] = path;
277 }
278 require(config.loaderConfig);
279
280 if(!config.modules){
281 config.modules = [];
282 }
283 // add dojox/app lifecycle module by default
284 config.modules.push("./module/lifecycle");
285 var modules = config.modules.concat(config.dependencies?config.dependencies:[]);
286
287 if(config.template){
288 path = config.template;
289 if(path.indexOf("./") == 0){
290 path = "app/"+path;
291 }
292 modules.push("dojo/text!" + path);
293 }
294
295 require(modules, function(){
296 var modules = [Application];
297 for(var i = 0; i < config.modules.length; i++){
298 modules.push(arguments[i]);
299 }
300
301 if(config.template){
302 var ext = {
303 templateString: arguments[arguments.length - 1]
304 }
305 }
306 App = declare(modules, ext);
307
308 ready(function(){
309 var app = new App(config, node || win.body());
310
311 if(has("app-log-api")){
312 app.log = function(){
313 // summary:
314 // If config is set to turn on app logging, then log msg to the console
315 //
316 // arguments:
317 // the message to be logged,
318 // all but the last argument will be treated as Strings and be concatenated together,
319 // the last argument can be an object it will be added as an argument to the console.log
320 var msg = "";
321 try{
322 for(var i = 0; i < arguments.length-1; i++){
323 msg = msg + arguments[i];
324 }
325 console.log(msg,arguments[arguments.length-1]);
326 }catch(e){}
327 };
328 }else{
329 app.log = function(){}; // noop
330 }
331
332 app.transitionToView = function(/*DomNode*/target, /*Object*/transitionOptions, /*Event?*/triggerEvent){
333 // summary:
334 // A convenience function to fire the transition event to transition to the view.
335 //
336 // target:
337 // The DOM node that initiates the transition (for example a ListItem).
338 // transitionOptions:
339 // Contains the transition options.
340 // triggerEvent:
341 // The event that triggered the transition (for example a touch event on a ListItem).
342 var opts = {bubbles:true, cancelable:true, detail: transitionOptions, triggerEvent: triggerEvent || null};
343 on.emit(target,"startTransition", opts);
344 };
345
346 app.setStatus(app.lifecycle.STARTING);
347 // Create global namespace for application.
348 // The global name is application id. ie: modelApp
349 var globalAppName = app.id;
350 if(window[globalAppName]){
351 declare.safeMixin(app, window[globalAppName]);
352 }
353 window[globalAppName] = app;
354 app.start();
355 });
356 });
357 }
358
359 return function(config, node){
360 if(!config){
361 throw new Error("App Config Missing");
362 }
363
364 if(config.validate){
365 require(["dojox/json/schema", "dojox/json/ref", "dojo/text!dojox/application/schema/application.json"], function(schema, appSchema){
366 schema = dojox.json.ref.resolveJson(schema);
367 if(schema.validate(config, appSchema)){
368 generateApp(config, node);
369 }
370 });
371 }else{
372 generateApp(config, node);
373 }
374 }
375 });