【问题标题】:getJSON internal event encountering Reference Error on passed-in function callgetJSON 内部事件在传入函数调用时遇到引用错误
【发布时间】:2012-09-27 20:36:11
【问题描述】:

我有一个使用 JSON 调用 MVC 控制器来填充表的方法,如下所示:

pub.PopulateTable = function (args) {
    var page = 1,
        // ...variables snipped...
        OnRowClicked;

    // Unpack arguments...
    if (args != null) {
        // ...details snipped...

        OnRowClicked = args.OnRowClicked;
    }

    // Build path...
    path = path + controller + '/' + action + '/';
    if (actionId != null && actionId != '') {
        path = path + actionId + '/';
    }
    path = path + page;

    $.getJSON(path, function (data) {
        if (data.Values.length > 0) {
            // Clear table body, then inject list...
            $tableBody.html('');
            $.tmpl($template, data.Values).appendTo($tableBody);

            // ...snip various instructions, for brevity...

            // Add on-click returning...
            $('tr').click(function () {
                var $row = $(this),
                    rowData = {};

                rowData.SomeProperty = $row.children('#IdColumn').val();

                $modalDialog.modal('hide');
                OnRowClicked(rowData);  // Problem!!!
            });
        } else {
            $tableBody.html("<tr><td colspan=2>No entries...</td></tr>");
        }
    });

也许是因为 getJSON 是一个异步操作,但是通过方法参数对象传入的 OnRowClicked() 方法在尝试使用以下传入的(简单)方法时遇到了引用错误:

function textFieldRowClickHandler(rowData) {
    $myTextFieldHere.val(rowData.SomeProperty);
}

当我打开对话框(这会导致 PopulateTable 运行并绑定其中的事件)并选择一条记录(从而触发 click 事件)时,我不断收到引用错误,因为 rowData.SomeProperty 未定义,甚至虽然回调将点击事件绑定到每个 tr 标签,当它被点击时,关闭对话框,获取值,构建一个对象,并将其传递给给定的方法。

如上所述 - 我知道 getJSON 是一个异步操作,这就是我认为我的问题出现的地方 - 我不熟悉异步范式。我到底做错了什么?

【问题讨论】:

  • 我看不出你的代码有什么问题,除了 rowData 没有SomeProperty 属性,它只有ID
  • 哎呀!接得好!但我的意思是 SomeProperty,而不是 ID。编辑:更新了代码;我确实确保我的代码有正确设置的变量,只是为了排除这种情况。

标签: javascript jquery asp.net-mvc-3 html asynchronous


【解决方案1】:

似乎 OnRowClicked 方法在调用时没有正确设置上下文。

你可以使用:

OnRowClicked = args.OnRowClicked.bind(args);

OnRowClicked = $.proxy(args.OnRowClicked,args);

所以它应该看起来像:

pub.PopulateTable = function (args) {
var page = 1,
    // ...variables snipped...
    OnRowClicked;

// Unpack arguments...
if (args != null) {
    // ...details snipped...

    OnRowClicked = args.OnRowClicked.bind(args);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多