Alexander Tyapkov
Alexander Tyapkov

Reputation: 5067

Setup semantic-ui-calendar once for multiple usage in multiple js files

I have Django app which uses webpack to compile frontend. As a frontend library I am using semantic-ui. Recently I have installed separate module semantic-ui-calendar.

It is working fine. In required js file I can write

  $('#event_starts_at_1').calendar({
      minDate: new Date(today.getFullYear(), today.getMonth(), today.getDate(), today.getHours(), today.getMinutes()),
      monthFirst: false,
  });

and it will init the calendar component.

The ui-calendar component uses many options which I will use. Also I have multiple pages where ui-calendar will be embedded.

I don't want to repeat the same code for ui-calendar initialization in each of js files and looking for a solution which inits the component only once.

For me the problem looks not very complecated but I cannot figure out how to solve it with js and webpack. Probably you can provide some snippet which either subclasses ui-calendar or does something else to setup it only once. Thanks!

Upvotes: 0

Views: 435

Answers (1)

jumps4fun
jumps4fun

Reputation: 4130

I can see you are aleady using JQuery, so here is a suggestion. Note that there are several different ways of doing this, and this is only one approach.

If you do not wish to initialize each element in its own javascript, as you have written in your example in the question, you can always abstract it away.

you can consider giving all of your calendar elements a classname like semantic-calendar. Then, in a javascript file, use a document-ready function, and a foreach loop to initialize all elements with the given class:

$( document ).ready(function() {
    $('.semantic-calendar').each(function(){ 
        $(this).calendar({
            minDate: new Date(today.getFullYear(), today.getMonth(), 
                today.getDate(), today.getHours(), today.getMinutes()),
            monthFirst: false
        });
    });
});

Note that the last comma after false has been removed. it shouldn't be there, as it is the last element.

Now, this javascript snippet could be included in the calendar js itself, if you have control of it. It can also be included as a seperate file, or an existing custom javascript utility collection.

If needed, you could always skip the document-ready wrapper, and put the code inside a function instead. That way you would decide yourself when the initialization happens, by calling a function, instead of it happening automatically when the DOM is loaded.

Upvotes: 1

Related Questions