Search code examples
javascriptjquerymodel-view-controllermodule-pattern

Why is my class undefined at runtime. Javascript module pattern


When i run my application i get: "Uncaught TypeError: Cannot read property 'init' of undefined" The alert in the document reasdy function runs, so i know jQuery is loaded at that point. But i don't know why Task is undefined.

This is in a MVC5 application, and running jQuery 1.10.2

Please help, jsFiddle works fine, and JsHint shows no errors.

    var Task = (function () {

    var initialize = function () {
        console.log($);
        bindEvents();
    };
    var postFilter = function () {
        console.log("clicked");
        var postData = {
            UserID: $('#user_select').val,
            TaskTypeID: $('#taskTypeSelect').val,
            TaskStatusID: $('#status_select').val,
            PriorityID: $('#priority_select').val
        };

        $.ajax({
            url: "/Tasks/_AllTaskView",
            data: postData,
            success: function (response) {
                $('#results').html(response);
            }

        });
    };

    var bindEvents = function () {
        $('#submit_filter').on('click', postFilter);
    };

    return
    {
        init : initialize

    };

})();

$(document).ready(function () {
    alert()
    Task.init();
});

Solution

  • Put the curly brace of your return on the same line as return.

    Instead of:

    return
    {
        init : initialize
    
    };
    

    Do this:

    return {
        init : initialize
    };
    

    JavaScript has automatic semi-colon insertion which will automatically end the return statement before it hits the curly brace.