Wiki source code of XWiki JavaScript API
Last modified by Simon Urli on 2024/09/24
Show last authors
author | version | line-number | content |
---|---|---|---|
1 | {{box cssClass="floatinginfobox" title="**Contents**"}} | ||
2 | {{toc/}} | ||
3 | {{/box}} | ||
4 | |||
5 | = Observable XWiki Events = | ||
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 | |||
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: | ||
10 | |||
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(); | ||
15 | |||
16 | // The event can have an option memo object to pass to its observers some information: | ||
17 | console.log(event.memo.somethingINeedToKnow); | ||
18 | }); | ||
19 | {{/code}} | ||
20 | |||
21 | Check out the real examples below or read more about [[Prototype.js's event system>>http://prototypejs.org/doc/latest/dom/Element/fire/]]. | ||
22 | |||
23 | == DOM Events (xwiki.js) == | ||
24 | |||
25 | * ((( | ||
26 | **##xwiki:dom:loaded##** | ||
27 | 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: | ||
28 | |||
29 | ((( | ||
30 | {{code language="javascript"}} | ||
31 | document.observe("xwiki:dom:loaded", function(){ | ||
32 | // Initialization that can rely on the fact the DOM is XWiki-tranformed goes here. | ||
33 | }); | ||
34 | {{/code}} | ||
35 | ))) | ||
36 | |||
37 | ((( | ||
38 | {{info}} | ||
39 | It is recommended to bind startup scripts to this event instead of ##window.load## or ##document.dom:loaded##. | ||
40 | {{/info}} | ||
41 | ))) | ||
42 | ))) | ||
43 | |||
44 | * **##xwiki:dom:loading##** | ||
45 | ##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. | ||
46 | * **##xwiki:dom:updated##** | ||
47 | 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:((( | ||
48 | {{code language="javascript"}} | ||
49 | var init = function(elements) { | ||
50 | // Search for special content to enhance in each DOM element in the "elements" list and enhance it | ||
51 | elements.each(function(element) { | ||
52 | element.select('.someBehavioralClass').each(function(item) { | ||
53 | enhance(item); | ||
54 | }); | ||
55 | }); | ||
56 | } | ||
57 | ['xwiki:dom:loaded', 'xwiki:dom:updated'].each(function(eventName) { | ||
58 | document.observe(eventName, function(event) { | ||
59 | init(event.memo && event.memo.elements || [document.documentElement]); | ||
60 | }); | ||
61 | }); | ||
62 | {{/code}} | ||
63 | |||
64 | {{warning}} | ||
65 | 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:((( | ||
66 | {{code}} | ||
67 | function init() { | ||
68 | // This is your initialization handler, that you generally hook to xwiki:dom:loaded | ||
69 | } | ||
70 | (XWiki && XWiki.domIsLoaded && init()) || document.observe("xwiki:dom:loaded", init); | ||
71 | {{/code}}))) | ||
72 | {{/warning}} | ||
73 | |||
74 | == Document content events (actionButtons.js) == | ||
75 | |||
76 | * **##xwiki:document:saved##** | ||
77 | This event is sent after the document has been successfully saved in an asynchronous request (i.e. after clicking the //Save and Continue// button). | ||
78 | * **##xwiki:document:saveFailed##** | ||
79 | 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##. | ||
80 | |||
81 | == Action events (actionButtons.js) == | ||
82 | |||
83 | * **##xwiki:actions:cancel##** | ||
84 | 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. | ||
85 | * **##xwiki:actions:beforePreview##** (7.4.1+, 8.0M1+) | ||
86 | 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. | ||
87 | * **##xwiki:actions:preview##** | ||
88 | 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. | ||
89 | * **##xwiki:actions:beforeSave##** (7.4.1+, 8.0M1+) | ||
90 | 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. | ||
91 | * ((( | ||
92 | **##xwiki:actions:save##** | ||
93 | 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: | ||
94 | |||
95 | ((( | ||
96 | {{code language="javascript"}} | ||
97 | document.observe("xwiki:actions:save", function(event){ | ||
98 | var doContinue = event.memo['continue']; | ||
99 | if (doContinue) { | ||
100 | // do something specific | ||
101 | } | ||
102 | }); | ||
103 | {{/code}} | ||
104 | ))) | ||
105 | |||
106 | ((( | ||
107 | {{warning}} | ||
108 | While most properties can be accessed as ##event.memo.property##, this doesn't work with ##event.memo.continue## since ##continue## is a reserved keyword. | ||
109 | {{/warning}} | ||
110 | ))) | ||
111 | |||
112 | ((( | ||
113 | 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. | ||
114 | ))) | ||
115 | ))) | ||
116 | |||
117 | == Document extra events (xwiki.js) == | ||
118 | |||
119 | * **##xwiki:docextra:loaded##** | ||
120 | 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.((( | ||
121 | {{code language="javascript"}} | ||
122 | document.observe("xwiki:docextra:loaded", function(event){ | ||
123 | var tabID = event.memo.id; | ||
124 | if (tabID == "attachments") { | ||
125 | // do something with the attachments tab retrieved content. | ||
126 | doSomething(event.memo.element); | ||
127 | } | ||
128 | }); | ||
129 | {{/code}} | ||
130 | ))) | ||
131 | * **##xwiki:docextra:activated##** | ||
132 | 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## | ||
133 | |||
134 | == Suggest events (ajaxSuggest.js) == | ||
135 | |||
136 | * **##xwiki:suggest:selected##** (since 2.3) | ||
137 | This event is fired on the target input when a value was selected. | ||
138 | |||
139 | == Fullscreen events (fullScreenEdit.js) == | ||
140 | |||
141 | * **##xwiki:fullscreen:enter##** (since 3.0 M3) (fired before entering full screen editing) | ||
142 | * **##xwiki:fullscreen:entered##** (since 2.5.1) (fired after entering full screen editing) | ||
143 | * **##xwiki:fullscreen:exit##** (since 3.0 M3) (fired before exiting full screen editing) | ||
144 | * **##xwiki:fullscreen:exited##** (since 2.5.1) (fired after exiting full screen editing) | ||
145 | * **##xwiki:fullscreen:resized##** (since 2.5.1) | ||
146 | |||
147 | All events have the target DOM element in ##event.memo.target##. | ||
148 | |||
149 | == Annotations events (AnnotationCode/Settings jsx) == | ||
150 | |||
151 | * **##xwiki:annotations:filter:changed##** | ||
152 | * **##xwiki:annotations:settings:loaded##** | ||
153 | |||
154 | == Livetable events (livetable.js) == | ||
155 | |||
156 | * **##xwiki:livetable:newrow##** (##event.memo.row## holds the new row) | ||
157 | * **##xwiki:livetable:loadingEntries##** (since 2.3 RC1) | ||
158 | * **##xwiki:livetable:receivedEntries##** (since 2.3 RC1) (##event.memo.data## contains the received JSON data) | ||
159 | * **##xwiki:livetable:loadingComplete##** (since 2.4 M1) (##event.memo.status## contains the response status code) | ||
160 | * **##xwiki:livetable:displayComplete##** (since 2.4 M1) | ||
161 | * **##xwiki:livetable:ready##** (since 2.4.4) | ||
162 | * **##xwiki:livetable:loading##** (since 3.1.1) (should be used in place of ##xwiki:dom:loading## to startup livetables) | ||
163 | |||
164 | 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##. | ||
165 | |||
166 | == Live Data events (Logic.js) == | ||
167 | |||
168 | * **##xwiki:livedata:instanceCreated##** (since 14.4 RC1) triggered when the DOM elements have been created and the instance initialized but potentially before entries are loaded | ||
169 | * ##**xwiki:livedata:beforeEntryFetch**## (since 13.4 RC1) | ||
170 | * ##**xwiki:livedata:afterEntryFetch**## (since 13.4 RC1) | ||
171 | * ##**xwiki:livedata:layoutChange**## (since 12.10) | ||
172 | * ##**xwiki:livedata:layoutLoaded**## (since 13.4 RC1) | ||
173 | * ##**xwiki:livedata:pageChange**## (since 12.10) with ##pageIndex## and ##previousPageIndex## | ||
174 | * ##**xwiki:livedata:pageSizeChange**## (since 12.10) with ##pageSize## and ##previousPageSize## | ||
175 | * ##**xwiki:livedata:select**## (since 12.10) with ##entry## | ||
176 | * ##**xwiki:livedata:deselect**## (since 12.10) with ##entry## | ||
177 | * ##**xwiki:livedata:selectGlobal**## (since 12.10) | ||
178 | * ##**xwiki:livedata:sort**## (since 12.10) with ##property##, ##level## or ##type, and ##descending | ||
179 | * ##**xwiki:livedata:filter**## (since 12.10) with ##type##, ##property## and ##removedFilters## or ##oldEntry##/##newEntry## | ||
180 | * ##**xwiki:livedata:entriesUpdated**## (since 14.8RC1) | ||
181 | |||
182 | All events are dispatched on the container that is wrapping the Live Data as native custom events. All events have the Live Data instance set as ##detail.livedata##. Additional properties are available depending on the event and the situation in which the event is triggered, some of them are listed above. Before 14.4RC1 and 13.10.6, the events were triggered on a detached DOM element and thus it was not really possible to register event listeners for them. | ||
183 | |||
184 | = RequireJS and jQuery APIs = | ||
185 | |||
186 | 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: | ||
187 | |||
188 | {{code language="javascript"}} | ||
189 | require(['jquery'], function ($) { | ||
190 | $('#xwikicontent').append('<p>Inside of this function, $ becomes jquery!</p>'); | ||
191 | }); | ||
192 | {{/code}} | ||
193 | |||
194 | 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. | ||
195 | |||
196 | == Deferred Dependency Loading == | ||
197 | |||
198 | 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(). | ||
199 | |||
200 | {{code language="js"}} | ||
201 | require.config({ | ||
202 | paths: { | ||
203 | module: "path/to/module" | ||
204 | }, | ||
205 | shim: { | ||
206 | module: { | ||
207 | exports: 'someGlobalVariable', | ||
208 | deps: ['anotherModule'] | ||
209 | } | ||
210 | } | ||
211 | }); | ||
212 | {{/code}} | ||
213 | |||
214 | 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: | ||
215 | |||
216 | {{code language="js"}} | ||
217 | require(['path/to/config'], function() { | ||
218 | require(['module'], function(module) { | ||
219 | // Do something with the module. | ||
220 | }); | ||
221 | }); | ||
222 | {{/code}} | ||
223 | |||
224 | 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: | ||
225 | |||
226 | {{code language="js"}} | ||
227 | require(['deferred!module'], function(modulePromise) { | ||
228 | modulePromise.done(function(module) { | ||
229 | // Do something with the module, if the module is loaded by someone else. | ||
230 | }); | ||
231 | }); | ||
232 | {{/code}} | ||
233 | |||
234 | 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). | ||
235 | |||
236 | Examples where this could be useful: | ||
237 | |||
238 | * extend the tree widget (if it's available on the current page) | ||
239 | * extend the WYSIWYG editor (if it's loaded on the current page) | ||
240 | |||
241 | An alternative is for each module that wants to support extensions to fire some custom events when they are loaded. | ||
242 | |||
243 | == Bridging custom XWiki events between Prototype and jQuery == | ||
244 | |||
245 | Starting with XWiki 6.4 you can catch from jQuery the custom XWiki events that are fired from Prototype. | ||
246 | |||
247 | {{code language="js"}} | ||
248 | require(['jquery', 'xwiki-events-bridge'], function($) { | ||
249 | $('.some-element').on('xwiki:moduleName:eventName', function(event, data) { | ||
250 | // Here, do something that will be executed at the moment the event is fired. | ||
251 | doSomething(); | ||
252 | |||
253 | // The passed data is a reference to the event.memo from Prototype. | ||
254 | console.log(data.somethingINeedToKnow); | ||
255 | }); | ||
256 | }); | ||
257 | {{/code}} | ||
258 | |||
259 | 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. | ||
260 | |||
261 | {{code language="js"}} | ||
262 | // Prototype (old code that you don't have time to rewrite) | ||
263 | document.observe('xwiki:dom:updated', function(event) { | ||
264 | event.memo.elements.each(function(element) { | ||
265 | // Do something. | ||
266 | }); | ||
267 | }); | ||
268 | ... | ||
269 | // jQuery (new code, in a different file/page) | ||
270 | require(['jquery', 'xwiki-events-bridge'], function($) { | ||
271 | $(document).trigger('xwiki:dom:updated', {'elements': $('.some-container').toArray()}); | ||
272 | }); | ||
273 | {{/code}} | ||
274 | |||
275 | = Get some information about the current document {{info}}(Since 6.3M2){{/info}} = | ||
276 | |||
277 | In your javascript's applications, you can get (meta) information about the current document, though an AMD module. | ||
278 | |||
279 | {{code language="javascript"}} | ||
280 | require(['xwiki-meta'], function (xm) { | ||
281 | xm.documentReference // since 7.3M2, get the reference of the current document (as a DocumentReference object). | ||
282 | xm.document // get the current document (eg: Main.WebHome) -- deprecated since 7.3M2, use documentReference instead | ||
283 | xm.wiki // get the current wiki (eg: xwiki) -- deprecated since 7.3M2, use documentReference instead | ||
284 | xm.space // get the current space (eg: Main) -- deprecated since 7.3M2, use documentReference instead | ||
285 | xm.page // get the current page name (eg: WebHome) -- deprecated since 7.3M2, use documentReference instead | ||
286 | xm.version // get the current document version (eg: 1.1) | ||
287 | xm.restURL // get the REST url of the current doc (eg: /xwiki/rest/wikis/xwiki/spaces/Main/pages/WebHome) | ||
288 | xm.form_token // get the current CSRF token that you should pass to your scripts to avoid CSRF attacks. | ||
289 | xm.userReference // since 10.4RC1 and 9.11.5, get the reference of the current user | ||
290 | xm.isNew // since 11.2RC1, define if the current document is new or not | ||
291 | xm.locale // since 12.3RC1, get the locale of the current document | ||
292 | }); | ||
293 | {{/code}} | ||
294 | |||
295 | {{warning}} | ||
296 | 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! | ||
297 | {{/warning}} | ||
298 | |||
299 | == Be retro-compatible with versions older than 6.3 == | ||
300 | |||
301 | If you want to be compatible with older version, you can use this trick: | ||
302 | |||
303 | {{code language="javascript"}} | ||
304 | require(['xwiki-meta'], function (xm) { | ||
305 | // Note that the require['xwiki-meta'] (meta information about the current document) is not available on | ||
306 | // XWiki versions < 6.3, then we get these meta information directly from the DOM. | ||
307 | var document = xm ? xm.document : $('meta[name="document"]').attr('content'); | ||
308 | var wiki = xm ? xm.wiki : $('meta[name="wiki"]').attr('content'); | ||
309 | var space = xm ? xm.space : $('meta[name="space"]').attr('content'); | ||
310 | var page = xm ? xm.wiki : $('meta[name="page"]').attr('content'); | ||
311 | var version = xm ? xm.version : $('meta[name="version"]').attr('content'); | ||
312 | var restURL = xm ? xm.restURL : $('meta[name="restURL"]').attr('content'); | ||
313 | var form_token = xm ? xm.form_token : $('meta[name="form_token"]').attr('content'); | ||
314 | }); | ||
315 | {{/code}} | ||
316 | |||
317 | = Work with Entity References {{info}}(Since 4.2M1){{/info}} = | ||
318 | |||
319 | You can resolve and serialize Entity References on the client side easily: | ||
320 | |||
321 | {{code language="js"}} | ||
322 | var documentReference = XWiki.Model.resolve('wiki:Space.Page', XWiki.EntityType.DOCUMENT); | ||
323 | var attachmentReference = new XWiki.AttachmentReference('logo.png', documentReference); | ||
324 | XWiki.Model.serialize(attachmentReference); | ||
325 | {{/code}} | ||
326 | |||
327 | 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]]. | ||
328 | |||
329 | Starting with XWiki 7.2M1 the ##XWiki.Model## JavaScript API is supporting nested spaces: | ||
330 | |||
331 | {{code language="js"}} | ||
332 | var documentReference = XWiki.Model.resolve('wiki:Path.To.My.Page', XWiki.EntityType.DOCUMENT); | ||
333 | documentReference.getReversedReferenceChain().map(function(entityReference) { | ||
334 | return entityReference.type + ': ' + entityReference.name | ||
335 | }).join() | ||
336 | // Will produce: | ||
337 | // 0: wiki,1: Path,1: To,1: My,2: Page | ||
338 | {{/code}} | ||
339 | |||
340 | 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. | ||
341 | |||
342 | {{code language="js"}} | ||
343 | var documentReference = XWiki.Model.resolve('Page', XWiki.EntityType.DOCUMENT, function(type) { | ||
344 | switch(type) { | ||
345 | case: XWiki.EntityType.WIKI: | ||
346 | return 'wiki'; | ||
347 | case: XWiki.EntityType.SPACE: | ||
348 | return 'Space'; | ||
349 | default: | ||
350 | return null; | ||
351 | } | ||
352 | }); | ||
353 | // Produces wiki:Space.Page | ||
354 | |||
355 | var documentReference = XWiki.Model.resolve('Page', XWiki.EntityType.DOCUMENT, ['wiki', 'Space']); | ||
356 | // Same output | ||
357 | |||
358 | var spaceReference = new XWiki.SpaceReference('wiki', 'Space'); | ||
359 | var documentReference = XWiki.Model.resolve('Page', XWiki.EntityType.DOCUMENT, spaceReference); | ||
360 | // Same output | ||
361 | {{/code}} | ||
362 | |||
363 | Starting with 7.2M2 you can construct Reference to Nested Spaces and a new ##equals()## method has been added. Examples using Jasmine: | ||
364 | |||
365 | {{code language="js"}} | ||
366 | // Construct a Nested Space reference | ||
367 | var reference = new XWiki.SpaceReference('wiki', ['space1', 'space2']); | ||
368 | expect(XWiki.Model.serialize(reference)).toEqual('wiki:space1.space2'); | ||
369 | reference = new XWiki.DocumentReference('wiki', ['space1', 'space2'], 'page'); | ||
370 | expect(XWiki.Model.serialize(reference)).toEqual('wiki:space1.space2.page'); | ||
371 | // Construct a non-Nested Space reference | ||
372 | reference = new XWiki.SpaceReference('wiki', 'space'); | ||
373 | expect(XWiki.Model.serialize(reference)).toEqual('wiki:space'); | ||
374 | // Try passing non-valid space parameters | ||
375 | expect(function() {new XWiki.SpaceReference('wiki', [])}).toThrow('Missing mandatory space name or invalid type for: []'); | ||
376 | expect(function() {new XWiki.SpaceReference('wiki', 12)}).toThrow('Missing mandatory space name or invalid type for: [12]'); | ||
377 | |||
378 | // Equals() examples | ||
379 | var reference1 = new XWiki.DocumentReference('wiki', ['space1', 'space2'], 'page'); | ||
380 | var reference2 = new XWiki.DocumentReference('wiki', ['space1', 'space2'], 'page'); | ||
381 | var reference3 = new XWiki.DocumentReference('wiki2', ['space1', 'space2'], 'page'); | ||
382 | expect(reference1.equals(reference2)).toBe(true); | ||
383 | expect(reference1.equals(reference3)).toBe(false); | ||
384 | {{/code}} | ||
385 | |||
386 | 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. | ||
387 | |||
388 | {{code}} | ||
389 | this.entities = XWiki.EntityReferenceTree.fromJSONObject(transport.responseText.evalJSON()); | ||
390 | {{/code}} | ||
391 | ))) | ||
392 | |||
393 | = Related = | ||
394 | |||
395 | {{velocity}} | ||
396 | #set($tag = 'javascript') | ||
397 | #set ($list = $xwiki.tag.getDocumentsWithTag($tag)) | ||
398 | ((( | ||
399 | (% class="xapp" %) | ||
400 | == $services.localization.render('xe.tag.alldocs', ["//${tag}//"]) == | ||
401 | |||
402 | #if ($list.size()> 0) | ||
403 | {{html}}#displayDocumentList($list false $blacklistedSpaces){{/html}} | ||
404 | #else | ||
405 | (% class='noitems' %)$services.localization.render('xe.tag.notags') | ||
406 | #end | ||
407 | ))) | ||
408 | {{/velocity}} | ||
409 | |||
410 | = Example of understanding initialization = | ||
411 | |||
412 | Here's an example of a JavaScript snippet to use in a JavaScript extension xobject to ensure it's properly initialized when the dom is loaded and updated: | ||
413 | |||
414 | {{code language="javascript"}} | ||
415 | require(['jquery'], function ($) { | ||
416 | var init = function(){ | ||
417 | // The actual code you want to initialize that might need some dom elements. | ||
418 | }; | ||
419 | $(document).on('xwiki:dom:updated', init) | ||
420 | $(init); | ||
421 | |||
422 | }); | ||
423 | {{/code}} | ||
424 | |||
425 | The call to ##$(init)## will call the function when the DOM is actually ready (see the [[jQuery documentation>>https://api.jquery.com/ready/]]), and the ###xwiki:dom:updated### listener allows to trigger initialization when the dom is actually updated, if there's some asynchronous mechanism that might change it. You should be careful to ensure that init method can be called several times without side effect. | ||
426 | |||
427 | == Old example == | ||
428 | |||
429 | {{warning}} | ||
430 | Please note that the following example is very specific: | ||
431 | |||
432 | * It applies to old JavaScript code written using Prototype.js. The more recent recommendation is to use RequireJS and JQuery. | ||
433 | * It doesn't apply fully to any page having a LiveTable because the Rights UI has custom code to load the LiveTable. | ||
434 | {{/warning}} | ||
435 | |||
436 | Let's take the example of the Rights page of the Admin UI and understand how its LiveTable is initialized. | ||
437 | |||
438 | The browser will read the HTML from top to bottom. We have the following HTML content: | ||
439 | |||
440 | {{code language="html"}} | ||
441 | ... | ||
442 | <head> | ||
443 | ... | ||
444 | <script type='text/javascript' src='/xwiki/resources/js/prototype/prototype.js?cache-version=1584467090000'></script> | ||
445 | ... | ||
446 | <script type='text/javascript' src='/xwiki/bin/skin/resources/js/xwiki/xwiki.js?cache-version=1584467090000&defer=false&minify=false'></script> | ||
447 | ... | ||
448 | <script type='text/javascript' src='/xwiki/bin/skin/resources/js/xwiki/table/livetable.js?cache-version=1584467090000&minify=false' defer='defer'></script> | ||
449 | ... | ||
450 | </head> | ||
451 | <body> | ||
452 | ... | ||
453 | function startup() { | ||
454 | ... Rights LT init... | ||
455 | } | ||
456 | ... | ||
457 | (XWiki && XWiki.isInitialized && startup()) || document.observe('xwiki:livetable:loading', startup); | ||
458 | ... | ||
459 | {{/code}} | ||
460 | |||
461 | So here are the steps performed: | ||
462 | |||
463 | 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. | ||
464 | 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. | ||
465 | 1. ##livetable.js## is not executed at this stage since it's marked as ##defer##. | ||
466 | 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. | ||
467 | 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. | ||
468 | 1. Now that the DOM has been read, the browser sends the ##DOMContentLoaded## event. | ||
469 | 1. Thus the prototype function is called and the ##dom:loaded## event is triggered. | ||
470 | 1. Thus the ##xwiki.js##'s ##initialize## function is called and the ##xwiki:dom:loading## event is fired. | ||
471 | 1. Thus the ##livetable.js##'s ##init## function is called and the ##xwiki:livetable:loading## event is fired. | ||
472 | 1. Thus the Rights UI's ##startup## function is called and its LiveTable is initialized. |