jmack
jmack

Reputation: 189

RequireJS returning a function from module to be used in template

I am wanting to create a function in a module which would work with various dependencies but called in the template, so far I have only received a function undefined error. Where am I going wrong, or is this simply not possible?

helper.js module

define(['aDependency'],function(){

    var sayHi = function(){
        console.log('Hi');
};
return{
    sayHi: sayHi
}

This module is required in my main file

requirejs(['lib/helper']);

And I would like to use the function in my template;

<button data-remodal-action="confirm" onClick="sayHi()"/>

However I am getting an undefinde function.

Any help greatly appreciated.

Cheers

Upvotes: 0

Views: 424

Answers (2)

Evgeny Sorokin
Evgeny Sorokin

Reputation: 730

It seems like you're trying to call sayHi function like it's in the global scope, but it's not because requirejs modules has isolated scope

To use it like this - <button data-remodal-action="confirm" onClick="sayHi()"/> you should do something like

requirejs(['lib/helper'], function(helper){
    window.sayHi = helper.sayHi;
});

But it's an antipattern to set global variables that will be call from HTML. I'd propose you to do something like this

HTML:

<button id="sayHiButton" data-remodal-action="confirm"></button>

JS:

requirejs(['lib/helper'], function(helper){
    document.getElementById('sayHiButton').addEventListener('click', function(){
         helper.sayHi();
    });
});

Upvotes: 1

vbilopav
vbilopav

Reputation: 156

You can't do that

<button data-remodal-action="confirm" onClick="sayHi()"/>

points to a global function.

Your sayHi() function is part of object which your helper module returns. That is not global at all. If you want to add that function as click event on a button, you must do that where it is visible.

That is inside helper module

define(['aDependency'],function(){

    var sayHi = function(){
        console.log('Hi');
    };
    $('button').click(sayHi);
return{
    sayHi: sayHi
}

or

inside module that uses helper module:

requirejs(['lib/helper'], function (helper) {
  $('button').click(helper.sayHi);
});

Upvotes: 0

Related Questions