-1

Can I call a function inside a Require.js module with the function name in a string ?

define(['jquery', function( $ ) {

    var init = function() {
        var elems = {};

        for( var x=0; x<$('.js-elem').length; x++ ) {
            elems[x] = {
                dom: {
                    el: $('.js-elem').eq(x)
                },
                get animation() {
                    return this.dom.el.data('animation');
                }
            }

            setEvents( elems[x] );
        }
    };

    var setEvents = function( elem ) {
        elem.dom.el.on('click', function( e ) {
            console.log( elem.animation ); // = String "anim1"
            this[ elem.animation ]( elem ) // = window.anim1 (Out of require.js module scope)
        });
    };

    var anim1 = function( elem ) {
        //...
    };

    return {
        init: init
    };

});
Simon Arnold
  • 15,849
  • 7
  • 67
  • 85

1 Answers1

1

No, you cannot refer to anim1 via a string. "Variable variables" only work with global variables, but anim1 is not global.

See "Variable" variables in Javascript? or these search results for alternatives.


Note: In case of this[ elem.animation ]( elem ), this does not refer to window. It refers to elem.dom.el, the element the handler was bound to.

But as I said, window[elem.animation] wouldn't work either, since anim1 is not global.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143