Wiki source code of XWiki JavaScript API

Last modified by Vincent Massol on 2020/03/23

Hide last authors
Manuel Smeria 17.3 1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
Sergiu Dumitriu 9.1 4
Manuel Smeria 17.3 5 = Observable XWiki Events =
Jerome 1.1 6
7 Stay in touch with what happens in the wiki! XWiki will fire custom javascript events on certain moment and upon certain actions that occur in the navigation flow.
8
Sergiu Dumitriu 9.1 9 Event names are build on the following model: ##xwiki:modulename:eventname##. Your JavaScript script or extension can get notified of such an event the following way:
Jerome 1.1 10
Sergiu Dumitriu 10.1 11 {{code language="javascript"}}
12 document.observe("xwiki:modulename:eventname", function(event) {
13 // Here, do something that will be executed at the moment the event is fired
14 doSomething();
Jerome 1.1 15
Sergiu Dumitriu 10.1 16 // The event can have an option memo object to pass to its observers some information:
17 console.log(event.memo.somethingINeedToKnow);
Sergiu Dumitriu 9.1 18 });
19 {{/code}}
Jerome 1.1 20
Manuel Smeria 17.3 21 Check out the real examples below or read more about [[Prototype.js's event system>>http://prototypejs.org/doc/latest/dom/Element/fire/]].
Jerome 1.1 22
Manuel Smeria 17.3 23 == DOM Events (xwiki.js) ==
Jerome 1.1 24
Sergiu Dumitriu 11.1 25 * **##xwiki:dom:loaded##**
Manuel Smeria 17.3 26 This event is similar to [[prototype's dom:loaded event>>http://prototypejs.org/doc/latest/dom/document/observe/]], with the difference that in the time-lapse between ##dom:loaded## and ##xwiki:dom:loaded##, XWiki may have transformed the DOM. Example of DOM transformations operated by XWiki is setting the right target of links that have rel="external" attribute so that the document can be XHTML valid and still have the desired effect, making internal rendering error messages expandable, insert document template handlers for links to non-existent documents, and so on. In the future there might be more transformations operated by XWiki upon DOM initialization. This event is meant for code to be notified of loading of the XWiki-transformed version of the initial DOM. As ##dom:loaded##, it can be used as follows:(((
Sergiu Dumitriu 17.2 27 {{code language="javascript"}}
Jerome 1.1 28 document.observe("xwiki:dom:loaded", function(){
Sergiu Dumitriu 10.1 29 // Initialization that can rely on the fact the DOM is XWiki-tranformed goes here.
Jerome 1.1 30 });
Vincent Massol 38.1 31 {{/code}}
32 )))(((
Manuel Smeria 17.3 33 {{info}}
34 It is recommended to bind startup scripts to this event instead of ##window.load## or ##document.dom:loaded##.
35 {{/info}}
36 )))
37
Sergiu Dumitriu 11.1 38 * **##xwiki:dom:loading##**
Sergiu Dumitriu 9.1 39 ##xwiki:dom:loading## is sent between ##dom:loaded## and ##xwiki:dom:loaded##, before XWiki changes the DOM. This is the event that should start all scripts making important DOM changes that other scripts should see.
Sergiu Dumitriu 16.1 40 * **##xwiki:dom:updated##**
Sergiu Dumitriu 17.1 41 This event is sent whenever an important change in the DOM occurs, such as loading new content in a dialog box or tab, or refreshing the document content. Scripts that add behavior to certain elements, or which enhance the DOM, should listen to this event as well and re-apply their initialization process on the updated content, the same way that the whole DOM is enhanced on ##xwiki:dom:loaded##. The list of new or updated elements is sent in the ##event.memo.elements## property. For example:(((
42 {{code language="javascript"}}
43 var init = function(elements) {
44 // Search for special content to enhance in each DOM element in the "elements" list and enhance it
45 elements.each(function(element) {
46 element.select('.someBehavioralClass').each(function(item) {
47 enhance(item);
Sergiu Dumitriu 17.2 48 });
49 });
Sergiu Dumitriu 17.1 50 }
51 ['xwiki:dom:loaded', 'xwiki:dom:updated'].each(function(eventName) {
52 document.observe(eventName, function(event) {
53 init(event.memo && event.memo.elements || [document.documentElement]);
Sergiu Dumitriu 17.2 54 });
Sergiu Dumitriu 17.1 55 });
56 {{/code}}
Sergiu Dumitriu 1.5 57
Denis Gervalle 15.1 58 {{warning}}
59 If your script is loaded **deferred**, all these events may be triggered **before your script is executed** and therefore **before it has the ablity to observe these events**. Since 3.1.1, to prevent your handler to never being called, never use ##dom:loaded## anymore, and check ##XWiki.isInitialized## before waiting for ##xwiki:dom:loading##, and ##XWiki.domIsLoaded## before waiting for ##xwiki:dom:loaded##. If the flag is true, you should proceed immediately with your handler. Here is a simple construct to properly handle this:(((
60 {{code}}
61 function init() {
62 // This is your initialization handler, that you generally hook to xwiki:dom:loaded
63 }
64 (XWiki && XWiki.domIsLoaded && init()) || document.observe("xwiki:dom:loaded", init);
65 {{/code}})))
66 {{/warning}}
67
Manuel Smeria 17.3 68 == Document content events (actionButtons.js) ==
Sergiu Dumitriu 3.1 69
Sergiu Dumitriu 10.1 70 * **##xwiki:document:saved##**
71 This event is sent after the document has been successfully saved in an asynchronous request (i.e. after clicking the //Save and Continue// button).
72 * **##xwiki:document:saveFailed##**
73 This event is sent when a save and continue attempt failed for some reason. The XMLHttpRequest response object is sent in the memo, as ##event.memo.response##.
Sergiu Dumitriu 3.1 74
Manuel Smeria 17.3 75 == Action events (actionButtons.js) ==
Jerome 1.1 76
Sergiu Dumitriu 9.1 77 * **##xwiki:actions:cancel##**
Sergiu Dumitriu 3.2 78 This event is sent after the user clicks the "Cancel" button of an editor (Wiki, WYSIWYG, object, rights, etc.), but before actually cancelling the edit.
Marius Dumitru Florea 36.1 79 * **##xwiki:actions:beforePreview##** (7.4.1+, 8.0M1+)
80 This event is sent after the user clicks the "Preview" button from an edit mode, but before the edit form is validated. You can use this event to update the form fields before they are submitted to the preview action.
81 * **##xwiki:actions:preview##**
82 This event is sent after the edit form has been validated, as a result of the user clicking the "Preview" button from an edit mode, but before the form is submitted. The event is fired only if the edit form is valid.
Marius Dumitru Florea 36.2 83 * **##xwiki:actions:beforeSave##** (7.4.1+, 8.0M1+)
Marius Dumitru Florea 36.1 84 This event is sent after the user clicks the "Save" or "Save & Continue" button from an edit mode, but before the edit form is validated. You can use this event to update the form fields before they are submitted to the save action.
Sergiu Dumitriu 11.1 85 * **##xwiki:actions:save##**
Marius Dumitru Florea 36.1 86 This event is sent after the edit form has been validated, as a result of the user clicking the "Save" or "Save & Continue" button from an edit mode, but before the form is submitted. The event is fired only if the edit form is valid. A memo is available if you need to know if the intend is to continue after the save, in ##event.memo['continue']##. You can use it as follows:(((
Sergiu Dumitriu 10.1 87 {{code language="javascript"}}
Sergiu Dumitriu 12.1 88 document.observe("xwiki:actions:save", function(event){
89 var doContinue = event.memo['continue'];
Sergiu Dumitriu 10.1 90 if (doContinue) {
91 // do something specific
92 }
Jerome 1.1 93 });
Vincent Massol 38.1 94 {{/code}}
95 )))(((
Manuel Smeria 17.3 96 {{warning}}
97 While most properties can be accessed as ##event.memo.property##, this doesn't work with ##event.memo.continue## since ##continue## is a reserved keyword.
98 {{/warning}}
Vincent Massol 38.1 99 )))(((
Sergiu Dumitriu 10.1 100 All these events contain as extra information, in the second parameter sent to event listeners (the memo), the original click event (if any, and which can be stopped to prevent the action from completing), and the form being submitted, as ##event.memo.originalEvent##, and ##event.memo.form## respectively.
Manuel Smeria 17.3 101 )))
Sergiu Dumitriu 1.5 102
Manuel Smeria 17.3 103 == Document extra events (xwiki.js) ==
Jerome 1.1 104
Sergiu Dumitriu 11.1 105 * **##xwiki:docextra:loaded##**
106 This event is fired upon reception of the content of a document footer tab by AJAX. This event is useful if you need to operate transformations of the received content. You can filter on which tab content to operate (comments or attachment or information or ...) using the event memo. The DOM element in which the retrieved content has been injected is also passed to facilitate transformations.(((
Sergiu Dumitriu 10.1 107 {{code language="javascript"}}
Jerome 1.1 108 document.observe("xwiki:docextra:loaded", function(event){
109 var tabID = event.memo.id;
110 if (tabID == "attachments") {
111 // do something with the attachments tab retrieved content.
112 doSomething(event.memo.element);
113 }
114 });
Sergiu Dumitriu 9.1 115 {{/code}}
Sergiu Dumitriu 10.1 116 )))
Sergiu Dumitriu 9.1 117 * **##xwiki:docextra:activated##**
118 This event is fired upon activation of a tab. It differs from the loaded event since tabs are loaded only once if the user clicks going back and forth between tabs. This event will notify of each tab activation, just after the tab content is actually made visible. The tab ID is passed in the memo as for ##xwiki:docextra:loaded##
Oana Florea 4.1 119
Manuel Smeria 17.3 120 == Suggest events (ajaxSuggest.js) ==
Ecaterina Moraru (Valica) 8.1 121
Sergiu Dumitriu 9.1 122 * **##xwiki:suggest:selected##** (since 2.3)
Sergiu Dumitriu 11.1 123 This event is fired on the target input when a value was selected.
Ecaterina Moraru (Valica) 8.1 124
Manuel Smeria 17.3 125 == Fullscreen events (fullScreenEdit.js) ==
Oana Florea 4.1 126
Marius Dumitru Florea 14.1 127 * **##xwiki:fullscreen:enter##** (since 3.0 M3) (fired before entering full screen editing)
128 * **##xwiki:fullscreen:entered##** (since 2.5.1) (fired after entering full screen editing)
129 * **##xwiki:fullscreen:exit##** (since 3.0 M3) (fired before exiting full screen editing)
130 * **##xwiki:fullscreen:exited##** (since 2.5.1) (fired after exiting full screen editing)
131 * **##xwiki:fullscreen:resized##** (since 2.5.1)
Ecaterina Moraru (Valica) 6.1 132
Sergiu Dumitriu 11.1 133 All events have the target DOM element in ##event.memo.target##.
134
Manuel Smeria 17.3 135 == Annotations events (AnnotationCode/Settings jsx) ==
Ecaterina Moraru (Valica) 6.1 136
Sergiu Dumitriu 9.1 137 * **##xwiki:annotations:filter:changed##**
138 * **##xwiki:annotations:settings:loaded##**
Ecaterina Moraru (Valica) 6.1 139
Manuel Smeria 17.3 140 == Livetable events (livetable.js) ==
Ecaterina Moraru (Valica) 6.1 141
Sergiu Dumitriu 11.1 142 * **##xwiki:livetable:newrow##** (##event.memo.row## holds the new row)
Sergiu Dumitriu 9.1 143 * **##xwiki:livetable:loadingEntries##** (since 2.3 RC1)
Sergiu Dumitriu 11.1 144 * **##xwiki:livetable:receivedEntries##** (since 2.3 RC1) (##event.memo.data## contains the received JSON data)
145 * **##xwiki:livetable:loadingComplete##** (since 2.4 M1) (##event.memo.status## contains the response status code)
Sergiu Dumitriu 9.1 146 * **##xwiki:livetable:displayComplete##** (since 2.4 M1)
147 * **##xwiki:livetable:ready##** (since 2.4.4)
Denis Gervalle 15.1 148 * **##xwiki:livetable:loading##** (since 3.1.1) (should be used in place of ##xwiki:dom:loading## to startup livetables)
Sergiu Dumitriu 11.1 149
150 The livetable sends both generic events, named as above, and events specific to each livetable, containing the table name on the third position, such as ##xwiki:livetable:alldocs:loadingEntries##. The generic event has the table name in the memo, as ##event.memo.tableId##.
Caleb James DeLisle 18.1 151
Caleb James DeLisle 19.1 152 = RequireJS and jQuery APIs =
Caleb James DeLisle 18.1 153
154 By default XWiki uses PrototypeJS which is bound to the $ symbol. Starting in XWiki 5.2, you may use jQuery by //requiring// it using the [[RequireJS>>http://requirejs.org/]] AMD standard. To do this you would write your code as follows:
155
156 {{code language="javascript"}}
157 require(['jquery'], function ($) {
158 $('#xwikicontent').append('<p>Inside of this function, $ becomes jquery!</p>');
159 });
160 {{/code}}
161
162 The best part is, any scripts which are loaded using require are loaded //asynchronously// (all at the same time) and if they are not required, they are never loaded at all.
Guillaume Delhumeau 20.1 163
Marius Dumitru Florea 37.1 164 == Deferred Dependency Loading ==
165
166 Loading (transitive) dependencies through RequireJS works if those modules are known by RequireJS. In order to make a module known you need to tell RequireJS where to load that module from. A module can be located in various places: in a WebJar, in the skin, in a JSX object or even in a file attached to a wiki page. If the module you need is common enough that is loaded on every page (like the 'jquery' module) then chances are it is already known (configured in javascript.vm). Otherwise you need to configure the dependency by using require.config().
167
168 {{code language="js"}}
169 require.config({
170 paths: {
171 module: "path/to/module"
172 },
173 shim: {
174 module: {
175 exports: 'someGlobalVariable',
176 deps: ['anotherModule']
177 }
178 }
179 });
180 {{/code}}
181
182 If two scripts need the same dependency then they will have to duplicate the require configuration. In order to avoid this you could move the configuration in a separate file and write something like this:
183
184 {{code language="js"}}
185 require(['path/to/config'], function() {
186 require(['module'], function(module) {
187 // Do something with the module.
188 });
189 });
190 {{/code}}
191
192 but you would still duplicate the configuration path in both scripts. Now, suppose that one of the scripts is only extending a feature provided by the dependency module. This means that it doesn't necessarily need to bring the dependency. It only needs to extend the module if it's present. This can be achieved starting with XWiki 8.1M1 like this:
193
194 {{code language="js"}}
195 require(['deferred!module'], function(modulePromise) {
196 modulePromise.done(function(module) {
197 // Do something with the module, if the module is loaded by someone else.
198 });
199 });
200 {{/code}}
201
202 In other words, the script says to RequireJS "let me know when this module is loaded by someone else" (someone else being an other script on the same page). This looks similar with the solution where the require configuration is in a separate file, but the advantage is that the path is not duplicated (i.e. we can move the module to a different path without affecting the scripts that use it).
203
204 Examples where this could be useful:
205
206 * extend the tree widget (if it's available on the current page)
207 * extend the WYSIWYG editor (if it's loaded on the current page)
208
209 An alternative is for each module that wants to support extensions to fire some custom events when they are loaded.
210
Marius Dumitru Florea 24.1 211 == Bridging custom XWiki events between Prototype and jQuery ==
Marius Dumitru Florea 23.1 212
213 Starting with XWiki 6.4 you can catch from jQuery the custom XWiki events that are fired from Prototype.
214
215 {{code language="js"}}
216 require(['jquery', 'xwiki-events-bridge'], function($) {
217 $('.some-element').on('xwiki:moduleName:eventName', function(event, data) {
218 // Here, do something that will be executed at the moment the event is fired.
219 doSomething();
220
221 // The passed data is a reference to the event.memo from Prototype.
222 console.log(data.somethingINeedToKnow);
223 });
224 });
225 {{/code}}
226
Marius Dumitru Florea 24.1 227 Starting with XWiki 7.1M1 the event listeners registered from Prototype are notified when a custom XWiki event is fired using the jQuery API. This doesn't mean you should write new event listeners using Prototype but that you can rely on existing event listeners until they are rewritten using jQuery.
228
229 {{code language="js"}}
230 // Prototype (old code that you don't have time to rewrite)
231 document.observe('xwiki:dom:updated', function(event) {
232 event.memo.elements.each(function(element) {
233 // Do something.
234 });
235 });
236 ...
Marius Dumitru Florea 24.2 237 // jQuery (new code, in a different file/page)
Marius Dumitru Florea 24.1 238 require(['jquery', 'xwiki-events-bridge'], function($) {
239 $(document).trigger('xwiki:dom:updated', {'elements': $('.some-container').toArray()});
240 });
241 {{/code}}
242
Guillaume Delhumeau 26.1 243 = Get some information about the current document {{info}}(Since 6.3M2){{/info}} =
Guillaume Delhumeau 20.1 244
Vincent Massol 33.2 245 In your javascript's applications, you can get (meta) information about the current document, though an AMD module.
Guillaume Delhumeau 21.1 246
Guillaume Delhumeau 20.1 247 {{code language="javascript"}}
248 require(['xwiki-meta'], function (xm) {
Guillaume Delhumeau 35.1 249 xm.documentReference // since 7.3M2, get the reference of the current document (as a DocumentReference object).
250 xm.document // get the current document (eg: Main.WebHome) -- deprecated since 7.3M2, use documentReference instead
251 xm.wiki // get the current wiki (eg: xwiki) -- deprecated since 7.3M2, use documentReference instead
252 xm.space // get the current space (eg: Main) -- deprecated since 7.3M2, use documentReference instead
253 xm.page // get the current page name (eg: WebHome) -- deprecated since 7.3M2, use documentReference instead
254 xm.version // get the current document version (eg: 1.1)
255 xm.restURL // get the REST url of the current doc (eg: /xwiki/rest/wikis/xwiki/spaces/Main/pages/WebHome)
256 xm.form_token // get the current CSRF token that you should pass to your scripts to avoid CSRF attacks.
Guillaume Delhumeau 43.1 257 xm.userReference // since 10.4RC1 and 9.11.5, get the reference of the current user
Guillaume Delhumeau 20.1 258 });
259 {{/code}}
Guillaume Delhumeau 22.1 260
261 {{warning}}
262 It is actually the only clean way. In the past, we used to add some <meta> tags in the <head> section of the page, but is not even valid in HTML5. So now we have introduced this API that we will maintain, meanwhile relying on any other element in the page could be broken in the future!
263 {{/warning}}
Guillaume Delhumeau 28.1 264
265 == Be retro-compatible with versions older than 6.3 ==
266
267 If you want to be compatible with older version, you can use this trick:
268
269 {{code language="javascript"}}
270 require(['xwiki-meta'], function (xm) {
271 // Note that the require['xwiki-meta'] (meta information about the current document) is not available on
272 // XWiki versions < 6.3, then we get these meta information directly from the DOM.
273 var document = xm ? xm.document : $('meta[name="document"]').attr('content');
274 var wiki = xm ? xm.wiki : $('meta[name="wiki"]').attr('content');
275 var space = xm ? xm.space : $('meta[name="space"]').attr('content');
276 var page = xm ? xm.wiki : $('meta[name="page"]').attr('content');
277 var version = xm ? xm.version : $('meta[name="version"]').attr('content');
278 var restURL = xm ? xm.restURL : $('meta[name="restURL"]').attr('content');
279 var form_token = xm ? xm.form_token : $('meta[name="form_token"]').attr('content');
Guillaume Delhumeau 30.1 280 });
Guillaume Delhumeau 28.1 281 {{/code}}
Marius Dumitru Florea 31.1 282
Marius Dumitru Florea 32.3 283 = Work with Entity References {{info}}(Since 4.2M1){{/info}} =
Marius Dumitru Florea 31.1 284
Marius Dumitru Florea 32.3 285 You can resolve and serialize Entity References on the client side easily:
Marius Dumitru Florea 31.1 286
287 {{code language="js"}}
288 var documentReference = XWiki.Model.resolve('wiki:Space.Page', XWiki.EntityType.DOCUMENT);
289 var attachmentReference = new XWiki.AttachmentReference('logo.png', documentReference);
290 XWiki.Model.serialize(attachmentReference);
291 {{/code}}
292
293 You can check the full API [[here>>https://github.com/xwiki/xwiki-platform/blob/master/xwiki-platform-core/xwiki-platform-web/src/main/webapp/resources/uicomponents/model/entityReference.js]].
294
Marius Dumitru Florea 32.2 295 Starting with XWiki 7.2M1 the ##XWiki.Model## JavaScript API is supporting nested spaces:
Marius Dumitru Florea 31.1 296
297 {{code language="js"}}
298 var documentReference = XWiki.Model.resolve('wiki:Path.To.My.Page', XWiki.EntityType.DOCUMENT);
299 documentReference.getReversedReferenceChain().map(function(entityReference) {
300 return entityReference.type + ': ' + entityReference.name
301 }).join()
302 // Will produce:
303 // 0: wiki,1: Path,1: To,1: My,2: Page
304 {{/code}}
305
Marius Dumitru Florea 32.1 306 Starting with 7.2M1 you can also pass a 'provider' as the third argument to ##XWiki.Model.resolve()##. The provider is used to fill missing references, and it is either a function that gets the entity type, an array of entity names or an entity reference.
Marius Dumitru Florea 31.1 307
308 {{code language="js"}}
309 var documentReference = XWiki.Model.resolve('Page', XWiki.EntityType.DOCUMENT, function(type) {
310 switch(type) {
311 case: XWiki.EntityType.WIKI:
312 return 'wiki';
313 case: XWiki.EntityType.SPACE:
314 return 'Space';
315 default:
316 return null;
317 }
318 });
319 // Produces wiki:Space.Page
320
321 var documentReference = XWiki.Model.resolve('Page', XWiki.EntityType.DOCUMENT, ['wiki', 'Space']);
322 // Same output
323
324 var spaceReference = new XWiki.SpaceReference('wiki', 'Space');
325 var documentReference = XWiki.Model.resolve('Page', XWiki.EntityType.DOCUMENT, spaceReference);
326 // Same output
327 {{/code}}
Vincent Massol 33.1 328
329 Starting with 7.2M2 you can construct Reference to Nested Spaces and a new ##equals()## method has been added. Examples using Jasmine:
330
331 {{code language="js"}}
332 // Construct a Nested Space reference
333 var reference = new XWiki.SpaceReference('wiki', ['space1', 'space2']);
334 expect(XWiki.Model.serialize(reference)).toEqual('wiki:space1.space2');
335 reference = new XWiki.DocumentReference('wiki', ['space1', 'space2'], 'page');
336 expect(XWiki.Model.serialize(reference)).toEqual('wiki:space1.space2.page');
337 // Construct a non-Nested Space reference
338 reference = new XWiki.SpaceReference('wiki', 'space');
339 expect(XWiki.Model.serialize(reference)).toEqual('wiki:space');
340 // Try passing non-valid space parameters
341 expect(function() {new XWiki.SpaceReference('wiki', [])}).toThrow('Missing mandatory space name or invalid type for: []');
342 expect(function() {new XWiki.SpaceReference('wiki', 12)}).toThrow('Missing mandatory space name or invalid type for: [12]');
343
344 // Equals() examples
345 var reference1 = new XWiki.DocumentReference('wiki', ['space1', 'space2'], 'page');
346 var reference2 = new XWiki.DocumentReference('wiki', ['space1', 'space2'], 'page');
347 var reference3 = new XWiki.DocumentReference('wiki2', ['space1', 'space2'], 'page');
348 expect(reference1.equals(reference2)).toBe(true);
349 expect(reference1.equals(reference3)).toBe(false);
350 {{/code}}
Thomas Mortagne 34.1 351
352 In 7.2M2 a new XWiki.EntityReferenceTree class which partially mimic Java EntityReferenceTree on Javascript side. There is not much yet, it was mostly introduced to make easier to manipulate a serialized Java EntityReferenceTree.
353
354 {{code}}
355 this.entities = XWiki.EntityReferenceTree.fromJSONObject(transport.responseText.evalJSON());
356 {{/code}}
Vincent Massol 38.1 357 )))
Oana Florea 43.2 358
Oana Florea 43.3 359 = Related =
Oana Florea 43.2 360 {{velocity}}
361 #set($tag = 'javascript')
362 #set ($list = $xwiki.tag.getDocumentsWithTag($tag))
363 (((
364 (% class="xapp" %)
Oana Florea 43.4 365 == $services.localization.render('xe.tag.alldocs', ["//${tag}//"]) ==
Oana Florea 43.2 366
367 #if ($list.size()> 0)
368 {{html}}#displayDocumentList($list false $blacklistedSpaces){{/html}}
369 #else
370 (% class='noitems' %)$services.localization.render('xe.tag.notags')
371 #end
372 )))
373 {{/velocity}}
Vincent Massol 44.1 374
375 = Example of understanding initialization =
376
Vincent Massol 44.2 377 {{warning}}
378 Please note that the following example is very specific:
379 * It applies to old JavaScript code written using Prototype.js. The more recent recommendation is to use RequireJS and JQuery.
380 * It doesn't apply fully to any page having a LiveTable because the Rights UI has custom code to load the LiveTable.
381 {{/warning}}
382
Vincent Massol 44.1 383 Let's take the example of the Rights page of the Admin UI and understand how its LiveTable is initialized.
384
385 The browser will read the HTML from top to bottom. We have the following HTML content:
386
387 {{code language='html'}}
388 ...
389 <head>
390 ...
391 <script type='text/javascript' src='/xwiki/resources/js/prototype/prototype.js?cache-version=1584467090000'></script>
392 ...
393 <script type='text/javascript' src='/xwiki/bin/skin/resources/js/xwiki/xwiki.js?cache-version=1584467090000&defer=false&amp;minify=false'></script>
394 ...
395 <script type='text/javascript' src='/xwiki/bin/skin/resources/js/xwiki/table/livetable.js?cache-version=1584467090000&minify=false' defer='defer'></script>
396 ...
397 </head>
398 <body>
399 ...
400 function startup() {
401 ... Rights LT init...
402 }
403 ...
404 (XWiki && XWiki.isInitialized && startup()) || document.observe('xwiki:livetable:loading', startup);
405 ...
406 {{/code}}
407
408 So here are the steps performed:
Vincent Massol 44.2 409 1. ##prototype.js## is executed first and registers a function ({{code}document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);{{/code}}) to execute when the ##DOMContentLoaded## event is sent. This event is sent after the DOM has been parsed, thus after the scripts of the page have been executed. The ##fireContentLoadedEvent## function will fire the [[##dom:loaded## event>>http://api.prototypejs.org/dom/document/observe/]] when called.
Vincent Massol 44.1 410 1. ##xwiki.js## is executed and registers a function ({{code}}document.observe("dom:loaded", XWiki.initialize.bind(XWiki)){{/code}}) to execute when the ##dom:loaded## event is sent. In turn it'll fire 2 events ##xwiki:dom:loading## and ##xwiki:dom:loaded## when called.
411 1. ##livetable.js## is not executed at this stage since it's marked as ##defer##.
412 1. The Rights UI is executed and {{code}}XWiki && XWiki.isInitialized && startup(){{/code}} evaluates to false since the XWiki object has not been initialized yet at this stage. However it registers a function for the ##xwiki:livetable:loading## event.
413 1. The browser gets to the end of the HTML, and [[reads the ##livetable.js## script that was marked as deferred>>https://javascript.info/onload-ondomcontentloaded#domcontentloaded]]. The following executes: {{code}}(XWiki.isInitialized && init()) || document.observe('xwiki:dom:loading', init);{{/code}}. The {{code}}XWiki && XWiki.isInitialized && startup(){{/code}} part evaluates to false since the XWiki object has not been initialized yet. The ##init## function is registered for the ##xwiki:dom:loading## event. When fired, it will trigger the ##xwiki:livetable:loading## event.
414 1. Now that the DOM has been read, the browser sends the ##DOMContentLoaded## event.
415 1. Thus the prototype function is called and the ##dom:loaded## event is triggered.
416 1. Thus the ##xwiki.js##'s ##initialize## function is called and the ##xwiki:dom:loading## event is fired.
417 1. Thus the ##livetable.js##'s ##init## function is called and the ##xwiki:livetable:loading## event is fired.
418 1. Thus the Rights UI's ##startup## function is called and its LiveTable is initialized.
419

Get Connected