Greek English
Είστε εδώ Αρχική » Προγραμματιστές » Tutorials » Πολλαπλά onload events

Πολλαπλά onload events

Τελευταία ενημέρωση από Elxis Team

Προσθέστε πολλαπλά on document load events με την συνάρτηση elxLoadEvent.

Από το Elxis 4.1 Ποσειδών μπορείτε να προσθέτετε πολλαπλά onload events χρησιμοποιώντας την ενσωματωμένη συνάρτηση javascript elxLoadEvent. Σε αυτό το άρθρο θα δούμε γιατί η χρήση της elxLoadEvent είναι ταυτόχρονα σημαντική και απαραίτητη και θα δούμε πως μπορούμε να την χρησιμοποιήσουμε.

The need for elxLoadEvent

Let's say you have a script that needs to be executed on document's load. For example we will alert a message when the page is fully loaded. We do that by adding the code below to the document's head section.

window.onload = function() { alert('Document loaded!'); }

In Elxis this task can be easily using the addScript method of the elxisDocument library.

$eDoc = eFactory::getDocument();
$eDoc->addScript('window.onload = function() { alert(\'Document loaded!\'); }');

Now, what if an other extension try to add an onload event the same way? The second onload event will overwrite the first one! So, the alert message "Document loaded!" will never be displayed. The first onload event will not be executed.

Only the last call of window.onload will be executed if you call it multiple times on the same page.

It is clear now that we need to bypass this problem, and Elxis 4.1 has a built-in solution for this, the elxLoadEvent function.


Usage of elxLoadEvent

The use of elxLoadEvent function is pretty simple. Just put the script you want to execute inside it and that's all.

elxLoadEvent('javascript function here to call on window load');

You can use the elxLoadEvent function unlimited times on the same page and be sure that all onload events will be executed just fine. Below you can see our previous example and some other onload calls.

$eDoc = eFactory::getDocument();
$eDoc->addScript('elxLoadEvent(function() { alert(\'Document loaded!\'); });');
$eDoc->addScript('elxLoadEvent(function() { alert(\'An other one!\'); });');
$eDoc->addScript('elxLoadEvent(somefunction());');
$eDoc->addScript('elxLoadEvent(myfunction(4, 3));');

You develop a module, a template, a plugin and you want add an onload event? Use elxLoadEvent, it will make sure your code will always work.



Έχει διαβαστεί 9315 φορές

Μπορείτε να αντιγράψετε, διανείμετε και παρουσιάσετε τα άρθρα αυτού του ιστότοπου για μη εμπορικούς σκοπούς.
Creative Commons 3.0