Javascript 传入函数调用时getJSON内部事件遇到引用错误
我有一个方法,使用对MVC控制器的JSON调用填充表,如下所示:Javascript 传入函数调用时getJSON内部事件遇到引用错误,javascript,jquery,asp.net-mvc-3,html,asynchronous,Javascript,Jquery,Asp.net Mvc 3,Html,Asynchronous,我有一个方法,使用对MVC控制器的JSON调用填充表,如下所示: pub.PopulateTable = function (args) { var page = 1, // ...variables snipped... OnRowClicked; // Unpack arguments... if (args != null) { // ...details snipped... OnRowClick
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>");
}
});
当我打开对话框(这会导致PopulateTable运行并绑定其中的事件)并选择一条记录(从而触发click事件关闭)时,我会不断收到一个引用错误,因为rowData.SomeProperty未定义,即使回调将click事件绑定到每个tr标记,当它被单击时,会关闭对话框,获取值,构建一个对象,并将其传递给给定的方法
如上所述-我知道getJSON是一个异步操作,我认为这就是我的问题所在-我不熟悉异步范例。我到底做错了什么?调用OnRowClicked方法时,上下文设置似乎不正确 您可以使用:
OnRowClicked = args.OnRowClicked.bind(args);
或
所以它应该看起来像:
pub.PopulateTable = function (args) {
var page = 1,
// ...variables snipped...
OnRowClicked;
// Unpack arguments...
if (args != null) {
// ...details snipped...
OnRowClicked = args.OnRowClicked.bind(args);
}
我看不出你的代码有什么问题,除了rowData没有
SomeProperty
属性之外,它只有ID
eep!抢手货但我指的是一些属性,而不是ID。编辑:更新代码;我确实确保我的代码正确设置了变量,只是为了排除这种可能性。
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);
}