lundi 27 février 2017

Using modular design pattern in Javascript with DOM selection all at once

I have been following the Modular Design Pattern for quite some time now and find it extremely useful as it helps in the well maintenance of code & separation of blocks into modules.

Regular usage of the modules with jQuery has raised an important question in my mind. Most of my applications/code follow the following structure:

(function() {
    var chat = {
        websocket: new WebSocket("ws://echo.websocket.org/"),
        that: this,
        init: function() {
            this.scrollToBottom();
            this.bindEvents();
            this.webSocketHandlers();
        },
        bindEvents: function() {
            this.toggleChat();
            this.filterPeople();
            this.compose();
        },
        elements: {
            indicator: $(".indicator"),
            statusText: $(".status-text"),
            chatHeadNames: $(".people li .name"),
            filterInput: $("#filter-input"),
            msgInput: $("#msg-input"),
            sendBtn: $(".send")
        },
        ...
        ...
        ...
        filterPeople: function() {
          var that = this;
          this.elements.chatHeadNames.each(function() {
              $(this).attr('data-search-term', $(this).text().toLowerCase());
          });
        },
        ...
        ...
        ...
        chat.init();

})();

What I would like to know is whether referencing all my elements via jQuery as part of a single variable chat.elements is a good practice?

One part of me tells that it indeed is a good way to reference all your selectors at once and cache them in variables so that multiple usage of the same element can be done with the cached variables (instead of multiple DOM selections).

Another part of me tell that this might be an anti-pattern and specific elements should be selected and cached locally when required.

I have used similar structures throughout and have got mixed responses about the code from everywhere. Nothing solid. Any help would be appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire