Question

I'm having troubles binding to the 'create' event of the widget that uses jQuery UI Widget Factory. It only happens if I'm binding to it outside the widget. Please see the snippet (simplified for testing purposes)

(function($){

    $.widget('pr.test', {
        options: {
            create: function(e){
                // Shows up in the console
                console.log('Widget created');
            }
        }
    });

})(jQuery);

And then later in some other file I'm binding to this event

jQuery(document).ready(function($){

    $('body').test().on('testcreate', function(){
        // Doesn't show up in the console
        console.log('Widget created');
    });

});

I'm aware that I could just do this

$('body').test({
    create: function(){
        console.log('Widget created')
    }
});

but I need to be able to bind to the event multiple times after the widget initalization. Can somebody please explain what the problem is? Thanks.

Was it helpful?

Solution

Answering my own question in case somebody has the same problems. My mistake was calling the .on() method after the widget initialization, while I should have called it before. From my understanding the script was unaware of any event handlers bound to the 'create' event when it was fired.

See this fiddle.

$.widget('pr.test', {
    options: {
        create: function(){
            console.log('Called from within the widget');
        }
    }
});

// Binding to the event before it is fired
$('body').on('testcreate', function(){
    console.log('Called from outside the widget');
});

$('body').test();

// Binding to the event after it is fired
$('body').on('testcreate', function(){
    console.log('This will not work');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top