Debian Codegraph @

dijit/_WidgetBase.js

raw symbols SCIP
1 define([
2 "require", // require.toUrl
3 "dojo/_base/array", // array.forEach array.map
4 "dojo/aspect",
5 "dojo/_base/config", // config.blankGif
6 "dojo/_base/connect", // connect.connect
7 "dojo/_base/declare", // declare
8 "dojo/dom", // dom.byId
9 "dojo/dom-attr", // domAttr.set domAttr.remove
10 "dojo/dom-class", // domClass.add domClass.replace
11 "dojo/dom-construct", // domConstruct.destroy domConstruct.place
12 "dojo/dom-geometry", // isBodyLtr
13 "dojo/dom-style", // domStyle.set, domStyle.get
14 "dojo/has",
15 "dojo/_base/kernel",
16 "dojo/_base/lang", // mixin(), isArray(), etc.
17 "dojo/on",
18 "dojo/ready",
19 "dojo/Stateful", // Stateful
20 "dojo/topic",
21 "dojo/_base/window", // win.body()
22 "./Destroyable",
23 "dojo/has!dojo-bidi?./_BidiMixin",
24 "./registry" // registry.getUniqueId(), registry.findWidgets()
25 ], function(require, array, aspect, config, connect, declare,
26 dom, domAttr, domClass, domConstruct, domGeometry, domStyle, has, kernel,
27 lang, on, ready, Stateful, topic, win, Destroyable, _BidiMixin, registry){
28
29 // module:
30 // dijit/_WidgetBase
31
32 // Flag to make dijit load modules the app didn't explicitly request, for backwards compatibility
33 has.add("dijit-legacy-requires", !kernel.isAsync);
34
35 // Flag to enable support for textdir attribute
36 has.add("dojo-bidi", false);
37
38
39 // For back-compat, remove in 2.0.
40 if(has("dijit-legacy-requires")){
41 ready(0, function(){
42 var requires = ["dijit/_base/manager"];
43 require(requires); // use indirection so modules not rolled into a build
44 });
45 }
46
47 // Nested hash listing attributes for each tag, all strings in lowercase.
48 // ex: {"div": {"style": true, "tabindex" true}, "form": { ...
49 var tagAttrs = {};
50
51 function getAttrs(obj){
52 var ret = {};
53 for(var attr in obj){
54 ret[attr.toLowerCase()] = true;
55 }
56 return ret;
57 }
58
59 function nonEmptyAttrToDom(attr){
60 // summary:
61 // Returns a setter function that copies the attribute to this.domNode,
62 // or removes the attribute from this.domNode, depending on whether the
63 // value is defined or not.
64 return function(val){
65 domAttr[val ? "set" : "remove"](this.domNode, attr, val);
66 this._set(attr, val);
67 };
68 }
69
70 function isEqual(a, b){
71 // summary:
72 // Function that determines whether two values are identical,
73 // taking into account that NaN is not normally equal to itself
74 // in JS.
75
76 return a === b || (/* a is NaN */ a !== a && /* b is NaN */ b !== b);
77 }
78
79 var _WidgetBase = declare("dijit._WidgetBase", [Stateful, Destroyable], {
80 // summary:
81 // Future base class for all Dijit widgets.
82 // description:
83 // Future base class for all Dijit widgets.
84 // _Widget extends this class adding support for various features needed by desktop.
85 //
86 // Provides stubs for widget lifecycle methods for subclasses to extend, like postMixInProperties(), buildRendering(),
87 // postCreate(), startup(), and destroy(), and also public API methods like set(), get(), and watch().
88 //
89 // Widgets can provide custom setters/getters for widget attributes, which are called automatically by set(name, value).
90 // For an attribute XXX, define methods _setXXXAttr() and/or _getXXXAttr().
91 //
92 // _setXXXAttr can also be a string/hash/array mapping from a widget attribute XXX to the widget's DOMNodes:
93 //
94 // - DOM node attribute
95 // | _setFocusAttr: {node: "focusNode", type: "attribute"}
96 // | _setFocusAttr: "focusNode" (shorthand)
97 // | _setFocusAttr: "" (shorthand, maps to this.domNode)
98 // Maps this.focus to this.focusNode.focus, or (last example) this.domNode.focus
99 //
100 // - DOM node innerHTML
101 // | _setTitleAttr: { node: "titleNode", type: "innerHTML" }
102 // Maps this.title to this.titleNode.innerHTML
103 //
104 // - DOM node innerText
105 // | _setTitleAttr: { node: "titleNode", type: "innerText" }
106 // Maps this.title to this.titleNode.innerText
107 //
108 // - DOM node CSS class
109 // | _setMyClassAttr: { node: "domNode", type: "class" }
110 // Maps this.myClass to this.domNode.className
111 //
112 // - Toggle DOM node CSS class
113 // | _setMyClassAttr: { node: "domNode", type: "toggleClass" }
114 // Toggles myClass on this.domNode by this.myClass
115 //
116 // If the value of _setXXXAttr is an array, then each element in the array matches one of the
117 // formats of the above list.
118 //
119 // If the custom setter is null, no action is performed other than saving the new value
120 // in the widget (in this).
121 //
122 // If no custom setter is defined for an attribute, then it will be copied
123 // to this.focusNode (if the widget defines a focusNode), or this.domNode otherwise.
124 // That's only done though for attributes that match DOMNode attributes (title,
125 // alt, aria-labelledby, etc.)
126
127 // id: [const] String
128 // A unique, opaque ID string that can be assigned by users or by the
129 // system. If the developer passes an ID which is known not to be
130 // unique, the specified ID is ignored and the system-generated ID is
131 // used instead.
132 id: "",
133 _setIdAttr: "domNode", // to copy to this.domNode even for auto-generated id's
134
135 // lang: [const] String
136 // Rarely used. Overrides the default Dojo locale used to render this widget,
137 // as defined by the [HTML LANG](http://www.w3.org/TR/html401/struct/dirlang.html#adef-lang) attribute.
138 // Value must be among the list of locales specified during by the Dojo bootstrap,
139 // formatted according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt) (like en-us).
140 lang: "",
141 // set on domNode even when there's a focus node. but don't set lang="", since that's invalid.
142 _setLangAttr: nonEmptyAttrToDom("lang"),
143
144 // dir: [const] String
145 // Bi-directional support, as defined by the [HTML DIR](http://www.w3.org/TR/html401/struct/dirlang.html#adef-dir)
146 // attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's
147 // default direction.
148 dir: "",
149 // set on domNode even when there's a focus node. but don't set dir="", since that's invalid.
150 _setDirAttr: nonEmptyAttrToDom("dir"), // to set on domNode even when there's a focus node
151
152 // class: String
153 // HTML class attribute
154 "class": "",
155 _setClassAttr: { node: "domNode", type: "class" },
156
157 // Override automatic assigning type --> focusNode, it causes exception on IE6-8.
158 // Instead, type must be specified as ${type} in the template, as part of the original DOM.
159 _setTypeAttr: null,
160
161 // style: String||Object
162 // HTML style attributes as cssText string or name/value hash
163 style: "",
164
165 // title: String
166 // HTML title attribute.
167 //
168 // For form widgets this specifies a tooltip to display when hovering over
169 // the widget (just like the native HTML title attribute).
170 //
171 // For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer,
172 // etc., it's used to specify the tab label, accordion pane title, etc. In this case it's
173 // interpreted as HTML.
174 title: "",
175
176 // tooltip: String
177 // When this widget's title attribute is used to for a tab label, accordion pane title, etc.,
178 // this specifies the tooltip to appear when the mouse is hovered over that text.
179 tooltip: "",
180
181 // baseClass: [protected] String
182 // Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate
183 // widget state.
184 baseClass: "",
185
186 // srcNodeRef: [readonly] DomNode
187 // pointer to original DOM node
188 srcNodeRef: null,
189
190 // domNode: [readonly] DomNode
191 // This is our visible representation of the widget! Other DOM
192 // Nodes may by assigned to other properties, usually through the
193 // template system's data-dojo-attach-point syntax, but the domNode
194 // property is the canonical "top level" node in widget UI.
195 domNode: null,
196
197 // containerNode: [readonly] DomNode
198 // Designates where children of the source DOM node will be placed.
199 // "Children" in this case refers to both DOM nodes and widgets.
200 // For example, for myWidget:
201 //
202 // | <div data-dojo-type=myWidget>
203 // | <b> here's a plain DOM node
204 // | <span data-dojo-type=subWidget>and a widget</span>
205 // | <i> and another plain DOM node </i>
206 // | </div>
207 //
208 // containerNode would point to:
209 //
210 // | <b> here's a plain DOM node
211 // | <span data-dojo-type=subWidget>and a widget</span>
212 // | <i> and another plain DOM node </i>
213 //
214 // In templated widgets, "containerNode" is set via a
215 // data-dojo-attach-point assignment.
216 //
217 // containerNode must be defined for any widget that accepts innerHTML
218 // (like ContentPane or BorderContainer or even Button), and conversely
219 // is null for widgets that don't, like TextBox.
220 containerNode: null,
221
222 // ownerDocument: [const] Document?
223 // The document this widget belongs to. If not specified to constructor, will default to
224 // srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global
225 ownerDocument: null,
226 _setOwnerDocumentAttr: function(val){
227 // this setter is merely to avoid automatically trying to set this.domNode.ownerDocument
228 this._set("ownerDocument", val);
229 },
230
231 /*=====
232 // _started: [readonly] Boolean
233 // startup() has completed.
234 _started: false,
235 =====*/
236
237 // attributeMap: [protected] Object
238 // Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute
239 // for each XXX attribute to be mapped to the DOM.
240 //
241 // attributeMap sets up a "binding" between attributes (aka properties)
242 // of the widget and the widget's DOM.
243 // Changes to widget attributes listed in attributeMap will be
244 // reflected into the DOM.
245 //
246 // For example, calling set('title', 'hello')
247 // on a TitlePane will automatically cause the TitlePane's DOM to update
248 // with the new title.
249 //
250 // attributeMap is a hash where the key is an attribute of the widget,
251 // and the value reflects a binding to a:
252 //
253 // - DOM node attribute
254 // | focus: {node: "focusNode", type: "attribute"}
255 // Maps this.focus to this.focusNode.focus
256 //
257 // - DOM node innerHTML
258 // | title: { node: "titleNode", type: "innerHTML" }
259 // Maps this.title to this.titleNode.innerHTML
260 //
261 // - DOM node innerText
262 // | title: { node: "titleNode", type: "innerText" }
263 // Maps this.title to this.titleNode.innerText
264 //
265 // - DOM node CSS class
266 // | myClass: { node: "domNode", type: "class" }
267 // Maps this.myClass to this.domNode.className
268 //
269 // If the value is an array, then each element in the array matches one of the
270 // formats of the above list.
271 //
272 // There are also some shorthands for backwards compatibility:
273 //
274 // - string --> { node: string, type: "attribute" }, for example:
275 //
276 // | "focusNode" ---> { node: "focusNode", type: "attribute" }
277 //
278 // - "" --> { node: "domNode", type: "attribute" }
279 attributeMap: {},
280
281 // _blankGif: [protected] String
282 // Path to a blank 1x1 image.
283 // Used by `<img>` nodes in templates that really get their image via CSS background-image.
284 _blankGif: config.blankGif || require.toUrl("dojo/resources/blank.gif"),
285
286 // textDir: String
287 // Bi-directional support, the main variable which is responsible for the direction of the text.
288 // The text direction can be different than the GUI direction by using this parameter in creation
289 // of a widget.
290 //
291 // This property is only effective when `has("dojo-bidi")` is defined to be true.
292 //
293 // Allowed values:
294 //
295 // 1. "" - default value; text is same direction as widget
296 // 2. "ltr"
297 // 3. "rtl"
298 // 4. "auto" - contextual the direction of a text defined by first strong letter.
299 textDir: "",
300
301 //////////// INITIALIZATION METHODS ///////////////////////////////////////
302
303 /*=====
304 constructor: function(params, srcNodeRef){
305 // summary:
306 // Create the widget.
307 // params: Object|null
308 // Hash of initialization parameters for widget, including scalar values (like title, duration etc.)
309 // and functions, typically callbacks like onClick.
310 // The hash can contain any of the widget's properties, excluding read-only properties.
311 // srcNodeRef: DOMNode|String?
312 // If a srcNodeRef (DOM node) is specified:
313 //
314 // - use srcNodeRef.innerHTML as my contents
315 // - if this is a behavioral widget then apply behavior to that srcNodeRef
316 // - otherwise, replace srcNodeRef with my generated DOM tree
317 },
318 =====*/
319
320 _introspect: function(){
321 // summary:
322 // Collect metadata about this widget (only once per class, not once per instance):
323 //
324 // - list of attributes with custom setters, storing in this.constructor._setterAttrs
325 // - generate this.constructor._onMap, mapping names like "mousedown" to functions like onMouseDown
326
327 var ctor = this.constructor;
328 if(!ctor._setterAttrs){
329 var proto = ctor.prototype,
330 attrs = ctor._setterAttrs = [], // attributes with custom setters
331 onMap = (ctor._onMap = {});
332
333 // Items in this.attributeMap are like custom setters. For back-compat, remove for 2.0.
334 for(var name in proto.attributeMap){
335 attrs.push(name);
336 }
337
338 // Loop over widget properties, collecting properties with custom setters and filling in ctor._onMap.
339 for(name in proto){
340 if(/^on/.test(name)){
341 onMap[name.substring(2).toLowerCase()] = name;
342 }
343
344 if(/^_set[A-Z](.*)Attr$/.test(name)){
345 name = name.charAt(4).toLowerCase() + name.substr(5, name.length - 9);
346 if(!proto.attributeMap || !(name in proto.attributeMap)){
347 attrs.push(name);
348 }
349 }
350 }
351
352 // Note: this isn't picking up info on properties like aria-label and role, that don't have custom setters
353 // but that set() maps to attributes on this.domNode or this.focusNode
354 }
355 },
356
357 postscript: function(/*Object?*/params, /*DomNode|String*/srcNodeRef){
358 // summary:
359 // Kicks off widget instantiation. See create() for details.
360 // tags:
361 // private
362
363 // Note that we skip calling this.inherited(), i.e. dojo/Stateful::postscript(), because 1.x widgets don't
364 // expect their custom setters to get called until after buildRendering(). Consider changing for 2.0.
365
366 this.create(params, srcNodeRef);
367 },
368
369 create: function(params, srcNodeRef){
370 // summary:
371 // Kick off the life-cycle of a widget
372 // description:
373 // Create calls a number of widget methods (postMixInProperties, buildRendering, postCreate,
374 // etc.), some of which of you'll want to override. See http://dojotoolkit.org/reference-guide/dijit/_WidgetBase.html
375 // for a discussion of the widget creation lifecycle.
376 //
377 // Of course, adventurous developers could override create entirely, but this should
378 // only be done as a last resort.
379 // params: Object|null
380 // Hash of initialization parameters for widget, including scalar values (like title, duration etc.)
381 // and functions, typically callbacks like onClick.
382 // The hash can contain any of the widget's properties, excluding read-only properties.
383 // srcNodeRef: DOMNode|String?
384 // If a srcNodeRef (DOM node) is specified:
385 //
386 // - use srcNodeRef.innerHTML as my contents
387 // - if this is a behavioral widget then apply behavior to that srcNodeRef
388 // - otherwise, replace srcNodeRef with my generated DOM tree
389 // tags:
390 // private
391
392 // First time widget is instantiated, scan prototype to figure out info about custom setters etc.
393 this._introspect();
394
395 // store pointer to original DOM tree
396 this.srcNodeRef = dom.byId(srcNodeRef);
397
398 // No longer used, remove for 2.0.
399 this._connects = [];
400 this._supportingWidgets = [];
401
402 // this is here for back-compat, remove in 2.0 (but check NodeList-instantiate.html test)
403 if(this.srcNodeRef && this.srcNodeRef.id && (typeof this.srcNodeRef.id == "string")){
404 this.id = this.srcNodeRef.id;
405 }
406
407 // mix in our passed parameters
408 if(params){
409 this.params = params;
410 lang.mixin(this, params);
411 }
412 this.postMixInProperties();
413
414 // Generate an id for the widget if one wasn't specified, or it was specified as id: undefined.
415 // Do this before buildRendering() because it might expect the id to be there.
416 if(!this.id){
417 this.id = registry.getUniqueId(this.declaredClass.replace(/\./g, "_"));
418 if(this.params){
419 // if params contains {id: undefined}, prevent _applyAttributes() from processing it
420 delete this.params.id;
421 }
422 }
423
424 // The document and <body> node this widget is associated with
425 this.ownerDocument = this.ownerDocument || (this.srcNodeRef ? this.srcNodeRef.ownerDocument : document);
426 this.ownerDocumentBody = win.body(this.ownerDocument);
427
428 registry.add(this);
429
430 this.buildRendering();
431
432 var deleteSrcNodeRef;
433
434 if(this.domNode){
435 // Copy attributes listed in attributeMap into the [newly created] DOM for the widget.
436 // Also calls custom setters for all attributes with custom setters.
437 this._applyAttributes();
438
439 // If srcNodeRef was specified, then swap out original srcNode for this widget's DOM tree.
440 // For 2.0, move this after postCreate(). postCreate() shouldn't depend on the
441 // widget being attached to the DOM since it isn't when a widget is created programmatically like
442 // new MyWidget({}). See #11635.
443 var source = this.srcNodeRef;
444 if(source && source.parentNode && this.domNode !== source){
445 source.parentNode.replaceChild(this.domNode, source);
446 deleteSrcNodeRef = true;
447 }
448
449 // Note: for 2.0 may want to rename widgetId to dojo._scopeName + "_widgetId",
450 // assuming that dojo._scopeName even exists in 2.0
451 this.domNode.setAttribute("widgetId", this.id);
452 }
453 this.postCreate();
454
455 // If srcNodeRef has been processed and removed from the DOM (e.g. TemplatedWidget) then delete it to allow GC.
456 // I think for back-compatibility it isn't deleting srcNodeRef until after postCreate() has run.
457 if(deleteSrcNodeRef){
458 delete this.srcNodeRef;
459 }
460
461 this._created = true;
462 },
463
464 _applyAttributes: function(){
465 // summary:
466 // Step during widget creation to copy widget attributes to the
467 // DOM according to attributeMap and _setXXXAttr objects, and also to call
468 // custom _setXXXAttr() methods.
469 //
470 // Skips over blank/false attribute values, unless they were explicitly specified
471 // as parameters to the widget, since those are the default anyway,
472 // and setting tabIndex="" is different than not setting tabIndex at all.
473 //
474 // For backwards-compatibility reasons attributeMap overrides _setXXXAttr when
475 // _setXXXAttr is a hash/string/array, but _setXXXAttr as a functions override attributeMap.
476 // tags:
477 // private
478
479 // Call this.set() for each property that was either specified as parameter to constructor,
480 // or is in the list found above. For correlated properties like value and displayedValue, the one
481 // specified as a parameter should take precedence.
482 // Particularly important for new DateTextBox({displayedValue: ...}) since DateTextBox's default value is
483 // NaN and thus is not ignored like a default value of "".
484
485 // Step 1: Save the current values of the widget properties that were specified as parameters to the constructor.
486 // Generally this.foo == this.params.foo, except if postMixInProperties() changed the value of this.foo.
487 var params = {};
488 for(var key in this.params || {}){
489 params[key] = this._get(key);
490 }
491
492 // Step 2: Call set() for each property with a non-falsy value that wasn't passed as a parameter to the constructor
493 array.forEach(this.constructor._setterAttrs, function(key){
494 if(!(key in params)){
495 var val = this._get(key);
496 if(val){
497 this.set(key, val);
498 }
499 }
500 }, this);
501
502 // Step 3: Call set() for each property that was specified as parameter to constructor.
503 // Use params hash created above to ignore side effects from step #2 above.
504 for(key in params){
505 this.set(key, params[key]);
506 }
507 },
508
509 postMixInProperties: function(){
510 // summary:
511 // Called after the parameters to the widget have been read-in,
512 // but before the widget template is instantiated. Especially
513 // useful to set properties that are referenced in the widget
514 // template.
515 // tags:
516 // protected
517 },
518
519 buildRendering: function(){
520 // summary:
521 // Construct the UI for this widget, setting this.domNode.
522 // Most widgets will mixin `dijit._TemplatedMixin`, which implements this method.
523 // tags:
524 // protected
525
526 if(!this.domNode){
527 // Create root node if it wasn't created by _TemplatedMixin
528 this.domNode = this.srcNodeRef || this.ownerDocument.createElement("div");
529 }
530
531 // baseClass is a single class name or occasionally a space-separated list of names.
532 // Add those classes to the DOMNode. If RTL mode then also add with Rtl suffix.
533 // TODO: make baseClass custom setter
534 if(this.baseClass){
535 var classes = this.baseClass.split(" ");
536 if(!this.isLeftToRight()){
537 classes = classes.concat(array.map(classes, function(name){
538 return name + "Rtl";
539 }));
540 }
541 domClass.add(this.domNode, classes);
542 }
543 },
544
545 postCreate: function(){
546 // summary:
547 // Processing after the DOM fragment is created
548 // description:
549 // Called after the DOM fragment has been created, but not necessarily
550 // added to the document. Do not include any operations which rely on
551 // node dimensions or placement.
552 // tags:
553 // protected
554 },
555
556 startup: function(){
557 // summary:
558 // Processing after the DOM fragment is added to the document
559 // description:
560 // Called after a widget and its children have been created and added to the page,
561 // and all related widgets have finished their create() cycle, up through postCreate().
562 //
563 // Note that startup() may be called while the widget is still hidden, for example if the widget is
564 // inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer.
565 // For widgets that need to do layout, it's best to put that layout code inside resize(), and then
566 // extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible.
567 if(this._started){
568 return;
569 }
570 this._started = true;
571 array.forEach(this.getChildren(), function(obj){
572 if(!obj._started && !obj._destroyed && lang.isFunction(obj.startup)){
573 obj.startup();
574 obj._started = true;
575 }
576 });
577 },
578
579 //////////// DESTROY FUNCTIONS ////////////////////////////////
580
581 destroyRecursive: function(/*Boolean?*/ preserveDom){
582 // summary:
583 // Destroy this widget and its descendants
584 // description:
585 // This is the generic "destructor" function that all widget users
586 // should call to cleanly discard with a widget. Once a widget is
587 // destroyed, it is removed from the manager object.
588 // preserveDom:
589 // If true, this method will leave the original DOM structure
590 // alone of descendant Widgets. Note: This will NOT work with
591 // dijit._TemplatedMixin widgets.
592
593 this._beingDestroyed = true;
594 this.destroyDescendants(preserveDom);
595 this.destroy(preserveDom);
596 },
597
598 destroy: function(/*Boolean*/ preserveDom){
599 // summary:
600 // Destroy this widget, but not its descendants. Descendants means widgets inside of
601 // this.containerNode. Will also destroy any resources (including widgets) registered via this.own().
602 //
603 // This method will also destroy internal widgets such as those created from a template,
604 // assuming those widgets exist inside of this.domNode but outside of this.containerNode.
605 //
606 // For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not
607 // depend on the current ability to destroy a widget without destroying its descendants. Generally
608 // they should use destroyRecursive() for widgets with children.
609 // preserveDom: Boolean
610 // If true, this method will leave the original DOM structure alone.
611 // Note: This will not yet work with _TemplatedMixin widgets
612
613 this._beingDestroyed = true;
614 this.uninitialize();
615
616 function destroy(w){
617 if(w.destroyRecursive){
618 w.destroyRecursive(preserveDom);
619 }else if(w.destroy){
620 w.destroy(preserveDom);
621 }
622 }
623
624 // Back-compat, remove for 2.0
625 array.forEach(this._connects, lang.hitch(this, "disconnect"));
626 array.forEach(this._supportingWidgets, destroy);
627
628 // Destroy supporting widgets, but not child widgets under this.containerNode (for 2.0, destroy child widgets
629 // here too). if() statement is to guard against exception if destroy() called multiple times (see #15815).
630 if(this.domNode){
631 array.forEach(registry.findWidgets(this.domNode, this.containerNode), destroy);
632 }
633
634 this.destroyRendering(preserveDom);
635 registry.remove(this.id);
636 this._destroyed = true;
637 },
638
639 destroyRendering: function(/*Boolean?*/ preserveDom){
640 // summary:
641 // Destroys the DOM nodes associated with this widget.
642 // preserveDom:
643 // If true, this method will leave the original DOM structure alone
644 // during tear-down. Note: this will not work with _Templated
645 // widgets yet.
646 // tags:
647 // protected
648
649 if(this.bgIframe){
650 this.bgIframe.destroy(preserveDom);
651 delete this.bgIframe;
652 }
653
654 if(this.domNode){
655 if(preserveDom){
656 domAttr.remove(this.domNode, "widgetId");
657 }else{
658 domConstruct.destroy(this.domNode);
659 }
660 delete this.domNode;
661 }
662
663 if(this.srcNodeRef){
664 if(!preserveDom){
665 domConstruct.destroy(this.srcNodeRef);
666 }
667 delete this.srcNodeRef;
668 }
669 },
670
671 destroyDescendants: function(/*Boolean?*/ preserveDom){
672 // summary:
673 // Recursively destroy the children of this widget and their
674 // descendants.
675 // preserveDom:
676 // If true, the preserveDom attribute is passed to all descendant
677 // widget's .destroy() method. Not for use with _Templated
678 // widgets.
679
680 // get all direct descendants and destroy them recursively
681 array.forEach(this.getChildren(), function(widget){
682 if(widget.destroyRecursive){
683 widget.destroyRecursive(preserveDom);
684 }
685 });
686 },
687
688 uninitialize: function(){
689 // summary:
690 // Deprecated. Override destroy() instead to implement custom widget tear-down
691 // behavior.
692 // tags:
693 // protected
694 return false;
695 },
696
697 ////////////////// GET/SET, CUSTOM SETTERS, ETC. ///////////////////
698
699 _setStyleAttr: function(/*String||Object*/ value){
700 // summary:
701 // Sets the style attribute of the widget according to value,
702 // which is either a hash like {height: "5px", width: "3px"}
703 // or a plain string
704 // description:
705 // Determines which node to set the style on based on style setting
706 // in attributeMap.
707 // tags:
708 // protected
709
710 var mapNode = this.domNode;
711
712 // Note: technically we should revert any style setting made in a previous call
713 // to his method, but that's difficult to keep track of.
714
715 if(lang.isObject(value)){
716 domStyle.set(mapNode, value);
717 }else{
718 if(mapNode.style.cssText){
719 mapNode.style.cssText += "; " + value;
720 }else{
721 mapNode.style.cssText = value;
722 }
723 }
724
725 this._set("style", value);
726 },
727
728 _attrToDom: function(/*String*/ attr, /*String*/ value, /*Object?*/ commands){
729 // summary:
730 // Reflect a widget attribute (title, tabIndex, duration etc.) to
731 // the widget DOM, as specified by commands parameter.
732 // If commands isn't specified then it's looked up from attributeMap.
733 // Note some attributes like "type"
734 // cannot be processed this way as they are not mutable.
735 // attr:
736 // Name of member variable (ex: "focusNode" maps to this.focusNode) pointing
737 // to DOMNode inside the widget, or alternately pointing to a subwidget
738 // tags:
739 // private
740
741 commands = arguments.length >= 3 ? commands : this.attributeMap[attr];
742
743 array.forEach(lang.isArray(commands) ? commands : [commands], function(command){
744
745 // Get target node and what we are doing to that node
746 var mapNode = this[command.node || command || "domNode"]; // DOM node
747 var type = command.type || "attribute"; // class, innerHTML, innerText, or attribute
748
749 switch(type){
750 case "attribute":
751 if(lang.isFunction(value)){ // functions execute in the context of the widget
752 value = lang.hitch(this, value);
753 }
754
755 // Get the name of the DOM node attribute; usually it's the same
756 // as the name of the attribute in the widget (attr), but can be overridden.
757 // Also maps handler names to lowercase, like onSubmit --> onsubmit
758 var attrName = command.attribute ? command.attribute :
759 (/^on[A-Z][a-zA-Z]*$/.test(attr) ? attr.toLowerCase() : attr);
760
761 if(mapNode.tagName){
762 // Normal case, mapping to a DOMNode. Note that modern browsers will have a mapNode.set()
763 // method, but for consistency we still call domAttr
764 domAttr.set(mapNode, attrName, value);
765 }else{
766 // mapping to a sub-widget
767 mapNode.set(attrName, value);
768 }
769 break;
770 case "innerText":
771 // Deprecated, use "textContent" instead.
772 mapNode.innerHTML = "";
773 mapNode.appendChild(this.ownerDocument.createTextNode(value));
774 break;
775 case "textContent":
776 mapNode.textContent = value;
777 break;
778 case "innerHTML":
779 mapNode.innerHTML = value;
780 break;
781 case "class":
782 domClass.replace(mapNode, value, this[attr]);
783 break;
784 case "toggleClass":
785 domClass.toggle(mapNode, command.className || attr, value);
786 break;
787 }
788 }, this);
789 },
790
791 get: function(name){
792 // summary:
793 // Get a property from a widget.
794 // name:
795 // The property to get.
796 // description:
797 // Get a named property from a widget. The property may
798 // potentially be retrieved via a getter method. If no getter is defined, this
799 // just retrieves the object's property.
800 //
801 // For example, if the widget has properties `foo` and `bar`
802 // and a method named `_getFooAttr()`, calling:
803 // `myWidget.get("foo")` would be equivalent to calling
804 // `widget._getFooAttr()` and `myWidget.get("bar")`
805 // would be equivalent to the expression
806 // `widget.bar2`
807 var names = this._getAttrNames(name);
808 return this[names.g] ? this[names.g]() : this._get(name);
809 },
810
811 set: function(name, value){
812 // summary:
813 // Set a property on a widget
814 // name:
815 // The property to set.
816 // value:
817 // The value to set in the property.
818 // description:
819 // Sets named properties on a widget which may potentially be handled by a
820 // setter in the widget.
821 //
822 // For example, if the widget has properties `foo` and `bar`
823 // and a method named `_setFooAttr()`, calling
824 // `myWidget.set("foo", "Howdy!")` would be equivalent to calling
825 // `widget._setFooAttr("Howdy!")` and `myWidget.set("bar", 3)`
826 // would be equivalent to the statement `widget.bar = 3;`
827 //
828 // set() may also be called with a hash of name/value pairs, ex:
829 //
830 // | myWidget.set({
831 // | foo: "Howdy",
832 // | bar: 3
833 // | });
834 //
835 // This is equivalent to calling `set(foo, "Howdy")` and `set(bar, 3)`
836
837 if(typeof name === "object"){
838 for(var x in name){
839 this.set(x, name[x]);
840 }
841 return this;
842 }
843 var names = this._getAttrNames(name),
844 setter = this[names.s];
845 if(lang.isFunction(setter)){
846 // use the explicit setter
847 var result = setter.apply(this, Array.prototype.slice.call(arguments, 1));
848 }else{
849 // Mapping from widget attribute to DOMNode/subwidget attribute/value/etc.
850 // Map according to:
851 // 1. attributeMap setting, if one exists (TODO: attributeMap deprecated, remove in 2.0)
852 // 2. _setFooAttr: {...} type attribute in the widget (if one exists)
853 // 3. apply to focusNode or domNode if standard attribute name, excluding funcs like onClick.
854 // Checks if an attribute is a "standard attribute" by whether the DOMNode JS object has a similar
855 // attribute name (ex: accept-charset attribute matches jsObject.acceptCharset).
856 // Note also that Tree.focusNode() is a function not a DOMNode, so test for that.
857 var defaultNode = this.focusNode && !lang.isFunction(this.focusNode) ? "focusNode" : "domNode",
858 tag = this[defaultNode] && this[defaultNode].tagName,
859 attrsForTag = tag && (tagAttrs[tag] || (tagAttrs[tag] = getAttrs(this[defaultNode]))),
860 map = name in this.attributeMap ? this.attributeMap[name] :
861 names.s in this ? this[names.s] :
862 ((attrsForTag && names.l in attrsForTag && typeof value != "function") ||
863 /^aria-|^data-|^role$/.test(name)) ? defaultNode : null;
864 if(map != null){
865 this._attrToDom(name, value, map);
866 }
867 this._set(name, value);
868 }
869 return result || this;
870 },
871
872 _attrPairNames: {}, // shared between all widgets
873 _getAttrNames: function(name){
874 // summary:
875 // Helper function for get() and set().
876 // Caches attribute name values so we don't do the string ops every time.
877 // tags:
878 // private
879
880 var apn = this._attrPairNames;
881 if(apn[name]){
882 return apn[name];
883 }
884 var uc = name.replace(/^[a-z]|-[a-zA-Z]/g, function(c){
885 return c.charAt(c.length - 1).toUpperCase();
886 });
887 return (apn[name] = {
888 n: name + "Node",
889 s: "_set" + uc + "Attr", // converts dashes to camel case, ex: accept-charset --> _setAcceptCharsetAttr
890 g: "_get" + uc + "Attr",
891 l: uc.toLowerCase() // lowercase name w/out dashes, ex: acceptcharset
892 });
893 },
894
895 _set: function(/*String*/ name, /*anything*/ value){
896 // summary:
897 // Helper function to set new value for specified property, and call handlers
898 // registered with watch() if the value has changed.
899 var oldValue = this[name];
900 this[name] = value;
901 if(this._created && !isEqual(oldValue, value)){
902 if(this._watchCallbacks){
903 this._watchCallbacks(name, oldValue, value);
904 }
905 this.emit("attrmodified-" + name, {
906 detail: {
907 prevValue: oldValue,
908 newValue: value
909 }
910 });
911 }
912 },
913
914 _get: function(/*String*/ name){
915 // summary:
916 // Helper function to get value for specified property stored by this._set(),
917 // i.e. for properties with custom setters. Used mainly by custom getters.
918 //
919 // For example, CheckBox._getValueAttr() calls this._get("value").
920
921 // future: return name in this.props ? this.props[name] : this[name];
922 return this[name];
923 },
924
925 emit: function(/*String*/ type, /*Object?*/ eventObj, /*Array?*/ callbackArgs){
926 // summary:
927 // Used by widgets to signal that a synthetic event occurred, ex:
928 // | myWidget.emit("attrmodified-selectedChildWidget", {}).
929 //
930 // Emits an event on this.domNode named type.toLowerCase(), based on eventObj.
931 // Also calls onType() method, if present, and returns value from that method.
932 // By default passes eventObj to callback, but will pass callbackArgs instead, if specified.
933 // Modifies eventObj by adding missing parameters (bubbles, cancelable, widget).
934 // tags:
935 // protected
936
937 // Specify fallback values for bubbles, cancelable in case they are not set in eventObj.
938 // Also set pointer to widget, although since we can't add a pointer to the widget for native events
939 // (see #14729), maybe we shouldn't do it here?
940 eventObj = eventObj || {};
941 if(eventObj.bubbles === undefined){
942 eventObj.bubbles = true;
943 }
944 if(eventObj.cancelable === undefined){
945 eventObj.cancelable = true;
946 }
947 if(!eventObj.detail){
948 eventObj.detail = {};
949 }
950 eventObj.detail.widget = this;
951
952 var ret, callback = this["on" + type];
953 if(callback){
954 ret = callback.apply(this, callbackArgs ? callbackArgs : [eventObj]);
955 }
956
957 // Emit event, but avoid spurious emit()'s as parent sets properties on child during startup/destroy
958 if(this._started && !this._beingDestroyed){
959 on.emit(this.domNode, type.toLowerCase(), eventObj);
960 }
961
962 return ret;
963 },
964
965 on: function(/*String|Function*/ type, /*Function*/ func){
966 // summary:
967 // Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }).
968 // type:
969 // Name of event (ex: "click") or extension event like touch.press.
970 // description:
971 // Call specified function when event `type` occurs, ex: `myWidget.on("click", function(){ ... })`.
972 // Note that the function is not run in any particular scope, so if (for example) you want it to run in the
973 // widget's scope you must do `myWidget.on("click", lang.hitch(myWidget, func))`.
974
975 // For backwards compatibility, if there's an onType() method in the widget then connect to that.
976 // Remove in 2.0.
977 var widgetMethod = this._onMap(type);
978 if(widgetMethod){
979 return aspect.after(this, widgetMethod, func, true);
980 }
981
982 // Otherwise, just listen for the event on this.domNode.
983 return this.own(on(this.domNode, type, func))[0];
984 },
985
986 _onMap: function(/*String|Function*/ type){
987 // summary:
988 // Maps on() type parameter (ex: "mousemove") to method name (ex: "onMouseMove").
989 // If type is a synthetic event like touch.press then returns undefined.
990 var ctor = this.constructor, map = ctor._onMap;
991 if(!map){
992 map = (ctor._onMap = {});
993 for(var attr in ctor.prototype){
994 if(/^on/.test(attr)){
995 map[attr.replace(/^on/, "").toLowerCase()] = attr;
996 }
997 }
998 }
999 return map[typeof type == "string" && type.toLowerCase()]; // String
1000 },
1001
1002 toString: function(){
1003 // summary:
1004 // Returns a string that represents the widget.
1005 // description:
1006 // When a widget is cast to a string, this method will be used to generate the
1007 // output. Currently, it does not implement any sort of reversible
1008 // serialization.
1009 return '[Widget ' + this.declaredClass + ', ' + (this.id || 'NO ID') + ']'; // String
1010 },
1011
1012 getChildren: function(){
1013 // summary:
1014 // Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent
1015 // is this widget. Note that it does not return all descendants, but rather just direct children.
1016 // Analogous to [Node.childNodes](https://developer.mozilla.org/en-US/docs/DOM/Node.childNodes),
1017 // except containing widgets rather than DOMNodes.
1018 //
1019 // The result intentionally excludes internally created widgets (a.k.a. supporting widgets)
1020 // outside of this.containerNode.
1021 //
1022 // Note that the array returned is a simple array. Application code should not assume
1023 // existence of methods like forEach().
1024
1025 return this.containerNode ? registry.findWidgets(this.containerNode) : []; // dijit/_WidgetBase[]
1026 },
1027
1028 getParent: function(){
1029 // summary:
1030 // Returns the parent widget of this widget.
1031
1032 return registry.getEnclosingWidget(this.domNode.parentNode);
1033 },
1034
1035 connect: function(/*Object|null*/ obj, /*String|Function*/ event, /*String|Function*/ method){
1036 // summary:
1037 // Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
1038 //
1039 // Connects specified obj/event to specified method of this object
1040 // and registers for disconnect() on widget destroy.
1041 //
1042 // Provide widget-specific analog to dojo.connect, except with the
1043 // implicit use of this widget as the target object.
1044 // Events connected with `this.connect` are disconnected upon
1045 // destruction.
1046 // returns:
1047 // A handle that can be passed to `disconnect` in order to disconnect before
1048 // the widget is destroyed.
1049 // example:
1050 // | var btn = new Button();
1051 // | // when foo.bar() is called, call the listener we're going to
1052 // | // provide in the scope of btn
1053 // | btn.connect(foo, "bar", function(){
1054 // | console.debug(this.toString());
1055 // | });
1056 // tags:
1057 // protected
1058
1059 return this.own(connect.connect(obj, event, this, method))[0]; // handle
1060 },
1061
1062 disconnect: function(handle){
1063 // summary:
1064 // Deprecated, will be removed in 2.0, use handle.remove() instead.
1065 //
1066 // Disconnects handle created by `connect`.
1067 // tags:
1068 // protected
1069
1070 handle.remove();
1071 },
1072
1073 subscribe: function(t, method){
1074 // summary:
1075 // Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead.
1076 //
1077 // Subscribes to the specified topic and calls the specified method
1078 // of this object and registers for unsubscribe() on widget destroy.
1079 //
1080 // Provide widget-specific analog to dojo.subscribe, except with the
1081 // implicit use of this widget as the target object.
1082 // t: String
1083 // The topic
1084 // method: Function
1085 // The callback
1086 // example:
1087 // | var btn = new Button();
1088 // | // when /my/topic is published, this button changes its label to
1089 // | // be the parameter of the topic.
1090 // | btn.subscribe("/my/topic", function(v){
1091 // | this.set("label", v);
1092 // | });
1093 // tags:
1094 // protected
1095 return this.own(topic.subscribe(t, lang.hitch(this, method)))[0]; // handle
1096 },
1097
1098 unsubscribe: function(/*Object*/ handle){
1099 // summary:
1100 // Deprecated, will be removed in 2.0, use handle.remove() instead.
1101 //
1102 // Unsubscribes handle created by this.subscribe.
1103 // Also removes handle from this widget's list of subscriptions
1104 // tags:
1105 // protected
1106
1107 handle.remove();
1108 },
1109
1110 isLeftToRight: function(){
1111 // summary:
1112 // Return this widget's explicit or implicit orientation (true for LTR, false for RTL)
1113 // tags:
1114 // protected
1115 return this.dir ? (this.dir.toLowerCase() == "ltr") : domGeometry.isBodyLtr(this.ownerDocument); //Boolean
1116 },
1117
1118 isFocusable: function(){
1119 // summary:
1120 // Return true if this widget can currently be focused
1121 // and false if not
1122 return this.focus && (domStyle.get(this.domNode, "display") != "none");
1123 },
1124
1125 placeAt: function(/*String|DomNode|DocumentFragment|dijit/_WidgetBase*/ reference, /*String|Int?*/ position){
1126 // summary:
1127 // Place this widget somewhere in the DOM based
1128 // on standard domConstruct.place() conventions.
1129 // description:
1130 // A convenience function provided in all _Widgets, providing a simple
1131 // shorthand mechanism to put an existing (or newly created) Widget
1132 // somewhere in the dom, and allow chaining.
1133 // reference:
1134 // Widget, DOMNode, DocumentFragment, or id of widget or DOMNode
1135 // position:
1136 // If reference is a widget (or id of widget), and that widget has an ".addChild" method,
1137 // it will be called passing this widget instance into that method, supplying the optional
1138 // position index passed. In this case position (if specified) should be an integer.
1139 //
1140 // If reference is a DOMNode (or id matching a DOMNode but not a widget),
1141 // the position argument can be a numeric index or a string
1142 // "first", "last", "before", or "after", same as dojo/dom-construct::place().
1143 // returns: dijit/_WidgetBase
1144 // Provides a useful return of the newly created dijit._Widget instance so you
1145 // can "chain" this function by instantiating, placing, then saving the return value
1146 // to a variable.
1147 // example:
1148 // | // create a Button with no srcNodeRef, and place it in the body:
1149 // | var button = new Button({ label:"click" }).placeAt(win.body());
1150 // | // now, 'button' is still the widget reference to the newly created button
1151 // | button.on("click", function(e){ console.log('click'); }));
1152 // example:
1153 // | // create a button out of a node with id="src" and append it to id="wrapper":
1154 // | var button = new Button({},"src").placeAt("wrapper");
1155 // example:
1156 // | // place a new button as the first element of some div
1157 // | var button = new Button({ label:"click" }).placeAt("wrapper","first");
1158 // example:
1159 // | // create a contentpane and add it to a TabContainer
1160 // | var tc = dijit.byId("myTabs");
1161 // | new ContentPane({ href:"foo.html", title:"Wow!" }).placeAt(tc)
1162
1163 var refWidget = !reference.tagName && registry.byId(reference);
1164 if(refWidget && refWidget.addChild && (!position || typeof position === "number")){
1165 // Adding this to refWidget and can use refWidget.addChild() to handle everything.
1166 refWidget.addChild(this, position);
1167 }else{
1168 // "reference" is a plain DOMNode, or we can't use refWidget.addChild(). Use domConstruct.place() and
1169 // target refWidget.containerNode for nested placement (position==number, "first", "last", "only"), and
1170 // refWidget.domNode otherwise ("after"/"before"/"replace"). (But not supported officially, see #14946.)
1171 var ref = refWidget && ("domNode" in refWidget) ?
1172 (refWidget.containerNode && !/after|before|replace/.test(position || "") ?
1173 refWidget.containerNode : refWidget.domNode) : dom.byId(reference, this.ownerDocument);
1174 domConstruct.place(this.domNode, ref, position);
1175
1176 // Start this iff it has a parent widget that's already started.
1177 // TODO: for 2.0 maybe it should also start the widget when this.getParent() returns null??
1178 if(!this._started && (this.getParent() || {})._started){
1179 this.startup();
1180 }
1181 }
1182 return this;
1183 },
1184
1185 defer: function(fcn, delay){
1186 // summary:
1187 // Wrapper to setTimeout to avoid deferred functions executing
1188 // after the originating widget has been destroyed.
1189 // Returns an object handle with a remove method (that returns null) (replaces clearTimeout).
1190 // fcn: Function
1191 // Function reference.
1192 // delay: Number?
1193 // Delay, defaults to 0.
1194 // tags:
1195 // protected
1196
1197 var timer = setTimeout(lang.hitch(this,
1198 function(){
1199 if(!timer){
1200 return;
1201 }
1202 timer = null;
1203 if(!this._destroyed){
1204 lang.hitch(this, fcn)();
1205 }
1206 }),
1207 delay || 0
1208 );
1209 return {
1210 remove: function(){
1211 if(timer){
1212 clearTimeout(timer);
1213 timer = null;
1214 }
1215 return null; // so this works well: handle = handle.remove();
1216 }
1217 };
1218 }
1219 });
1220
1221 if(has("dojo-bidi")){
1222 _WidgetBase.extend(_BidiMixin);
1223 }
1224
1225 return _WidgetBase;
1226 });