【问题标题】:Why is my class undefined at runtime. Javascript module pattern为什么我的类在运行时未定义。 Javascript 模块模式
【发布时间】:2015-02-10 01:26:52
【问题描述】:

当我运行我的应用程序时,我得到:“Uncaught TypeError: Cannot read property 'init' of undefined” 文档准备函数中的警报运行,所以我知道此时已加载 jQuery。但我不知道为什么 Task 是未定义的。

这是一个 MVC5 应用程序,运行 jQuery 1.10.2

请帮忙,jsFiddle 工作正常,JsHint 没有显示错误。

    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();
});

【问题讨论】:

  • 我赞成只是因为我不知道return 不允许它的值从后续行开始(每个 JS 编码人员都应该知道):)

标签: javascript jquery model-view-controller module-pattern


【解决方案1】:

return 的花括号与return 放在同一行。

代替:

return
{
    init : initialize

};

这样做:

return {
    init : initialize
};

JavaScript 具有自动分号插入功能,它会在 return 语句碰到花括号之前自动结束它。

【讨论】:

  • 我的错误(愚蠢的不一致的语言.. 任何一天给我 C#) - 评论被删除。嘿,它鼓励了其他 3 个支持...不要抱怨 :)
  • 作为一个完全没用的旁注,这个也可以:jsfiddle.net/3s6n4d5y/2
【解决方案2】:

在这里试试这个:

return{ init : function(){
                 initialize();
               }
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多