Blog navigation keyboard_arrow_down

Blog Rss rss_feed

Understanding JavaScript Architecture in PrestaShop

Understanding JavaScript Architecture in PrestaShop

JavaScript plays a crucial role in modern web development, especially in platforms like PrestaShop, where dynamic and interactive elements are necessary for a seamless user experience. Since version 1.7, PrestaShop has implemented a structured JavaScript architecture aimed at improving performance and supporting themes and modules.

Core JavaScript Files

On every PrestaShop page, two main JavaScript files are loaded:

  • core.js: This file initializes jQuery3, manages AJAX calls, and defines essential frontend methods.
  • theme.js: Contains theme-specific code and libraries tailored to the store’s design and functionality.

jQuery, provided by core.js, ensures consistency without the need for redefinition, optimizing resource management and improving load times.

Event Handling and Delegation

One of the key architectural decisions in PrestaShop’s JavaScript implementation is its robust event handling mechanism:

Dispatching Events

Events are dispatched using the prestashop.emit method, allowing modules and themes to trigger custom events with data payloads:

prestashop.emit('myEventName', { myData1: 1, myData2: 3 });
Listening to Events

Listeners can react to these events using prestashop.on, ensuring responsive behavior within the store:

if (typeof prestashop !== 'undefined') { prestashop.on('myEventName', function (event) { var eventDatas = {}; if (event && event.reason) { eventDatas = { my_data_1: event.reason.myData1, my_data_2: event.reason.myData2 }; } // Handle event data as needed }); }
Predefined Events

PrestaShop dispatches several predefined events from core.js, covering actions such as cart updates, address modifications, checkout steps, and product list updates. This structured event-driven approach ensures modularity and flexibility without direct DOM manipulation.

Event Delegation

To maintain event integrity after dynamic DOM updates (e.g., via AJAX), PrestaShop utilizes event delegation. This technique attaches events to parent elements, like body, ensuring handlers remain effective:

const body = $('body'); // Events delegated to the body element const event = jQuery.Event('click'); event.target = body.find('.js-theClassYouNeed'); body.trigger(event);

In conclusion, the adoption of structured JavaScript architecture in PrestaShop from version 1.7 exemplifies best web development practices. By leveraging jQuery for core functionalities, implementing robust event handling, and utilizing delegation, PrestaShop enhances performance and maintainability while simplifying the integration of custom features and modules.

Let us know in the comments how you feel about this JavaScript approach in PrestaShop!

Was this blog post helpful to you?

    
No comments at this moment
close

Checkout

close

Favourites