Peter de Groot
Peter de Groot

Reputation: 829

jQuery widget error: cannot call methods prior to initialization; attempted to call method

I'm new to writing custom jQuery widgets and i keep getting an error 'cannot call methods on demowidget prior to initialization; attempted to call method 'changeColor' on this code.

$.widget('my.demowidget', {
    _create: function () {
        this.element.on('change', 'select[name="color"]', function () {
            $(this).demowidget('changeColor');
        });

        this.createContent();
    },

    createContent: function () {
        var html = '';
        html += '<select name="color">';
        html += '<option value="green">Green</option>';
        html += '<option value="red">Red</option>';
        html += '</select>';
        html += '<div id="the-text">The text</div>';

        this.element.html(html);
    },

    changeColor: function() {
        $('#the-text').css('color', '#' + $('select[name="color"]'));
    }
});

$(document).ready(function () {
    $('#demo').demowidget();
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="demo">
</div>

How can i solve this problem so that the select-change event fires the changeColor function?

Upvotes: 1

Views: 641

Answers (1)

Quentin Roger
Quentin Roger

Reputation: 6538

You can initialize your widget before trying to call function :

$(this).demowidget().demowidget('changeColor');

Here a fiddle :

https://jsfiddle.net/mnfjtdz0/1/

Upvotes: 1

Related Questions