我在外部文件中定义了一个全局jQuery对象:
var App = function () {
function handleTableRowSelection()
{
/*
TRs being generated dynamically via json AJAX call.
Select nearest static element then pass in TRs.
*/
$('table.allow-selection tbody').on('click', 'tr', function(e)
{
/*Don't change row class if clicking on a link (HTMLAnchorElement), or any other sub-element*/
if ((e.target instanceof HTMLTableCellElement) == true)
{
var row = $(this);
row.find('td').each(function()
{
$(this).toggleClass('user-selected');
});
}
});
}
return {
init: function ()
{
handleTableRowSelection();
},
};
}();
当我调用App.init();在我的$ {document).ready中,即使我没有将任何参数传递给handleTableRowSelection,它也可以正常工作(从我的主刀片模板)。
当我尝试从子模板为单个视图调用
App.handleTableRowSelection('#details', 'table.allow-selection tbody tr')
时,出现“未定义不是函数”的消息。我在主模板中调用init方法,如下所示:
App.init();
我以为我可以访问App对象(我的IDE代码完成找到了它),不是这样吗?
最佳答案
将App
设置为IIFE,该返回返回包含{ init: <your function> }
的结构。没有其他功能暴露在IIFE之外-以这种方式使用时,这就是IIFE的全部要点:为功能提供“私有”存储并导出公共接口。
如果您希望能够使用该名称公开调用该函数,则最后一个return
需要使其在“正在导出”的对象上作为属性可用:
return {
init: function ()
{
handleTableRowSelection();
},
handleTableRowSelection: function () {
handleTableRowSelection();
}
};
关于jquery - JS全局对象,调用公共(public)方法时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24557330/