ES2015 import vs attach a function to a template?

There is a function that is used specifically for this template, but is put in a separate test-function.js file for better files organisation.


Is it better to attach the function to a template:

// ./lib/test-function.js
Template.Test_template.onCreated(function(){
   this.function = () => {};
});

and then import it to a main template file:

// test-template.js
import './lib/test-function.js'

Template.Test_template.onCreated(function(){
    this.testFunction();
    // some other on created code
});

…or have it as a separate function

// ./lib/test-function.js
export default function testFunction(){}

and import it into template file with:

// test-template.js
import testFunction from './lib/test-function.js'

Template.Test_template.onCreated(function(){
    testFunction();
    // some other on created code
});

I prefer the latter, but are there any caveats of doing that?

P.S. Long story short - what would happen if I don’t attach additional functions to a template instance but import them from separate files outside of specific template scope?

Attaching functions to the template instance is only important if they depend on the template instance itself. Otherwise, it’s better to use a standalone function that doesn’t know anything about the template. For example, formatDate() should be a standalone utility because it doesn’t have anything to do with templates, but initializeTemplateVariables() should be on a template if it wants to attach reactive vars etc.

1 Like