Question

I'm struggling on triggering a function which is defined in an object, by pointing to it using a dynamic key. My code looks something like this:

$(function(){
    var events = {
        Test : function(){
            console.log ('init');
        }
    }
    $('#trigger').click(function(){
        var e = $(this).data('event');
        events[e];
    });
});

So basically, there is some element #trigger with an attribute data-event="Test" (or something else), once it gets clicked I check the events object if there is a function defined for that trigger and fire it. However, it doesn't work this way. I can console log the events object but the function isn't executed. What am I doing wrong?

Thanks!

Was it helpful?

Solution

Invoke the function with ()

$('#trigger').click(function(){
        var e = $(this).data('event');
        events[e]();
        //       ^^this
});

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top