我有两个函数对两种不同的小部件类型执行相同的操作。我以为我已经找到了一种实现,它允许我使用一个通用函数而不是两个。我的想法是我会将每种类型的小部件传递给这个通用函数。但是,我在细节上苦苦挣扎:
这是我的两个函数,它们重复了很多代码:
buildTemplateLookupTreeDialog: function () {
lookupTreeViewDialog.bind('loaded.jstree', function () {
var templateID = workflowDialogContent.find('#DeviceTemplateID').val();
lookupTreeViewDialog.TemplateLookupTree('setSelectedNode', '#' + templateID);
lookupTreeViewDialog.TemplateLookupTree('saveCookie');
}).TemplateLookupTree();
lookupTreeViewDialog.TemplateLookupTree('onNodeDblClick', function (template) {
if (openDialog != null) {
openDialog.TemplateLookupTree('saveCookie');
openDialog.data('result', { id: template.id, name: template.name });
openDialog.dialog('close');
}
});
},
buildComponentLookupTreeDialog: function () {
lookupTreeViewDialog.bind('loaded.jstree', function () {
var componentID = workflowDialogContent.find('#DeviceComponentID').val();
lookupTreeViewDialog.ComponentLookupTree('setSelectedNode', '#' + componentID);
lookupTreeViewDialog.ComponentLookupTree('saveCookie');
}).ComponentLookupTree();
lookupTreeViewDialog.ComponentLookupTree('onNodeDblClick', function (component) {
if (openDialog != null) {
openDialog.ComponentLookupTree('saveCookie');
openDialog.data('result', { id: component.id, name: component.name });
openDialog.dialog('close');
}
});
}
这是我认为通用实现的样子:
buildGenericLookupTreeDialog: function (lookupTreeWidget, title, idSelector, nameSelector) {
lookupTreeViewDialog.bind('loaded.jstree', function () {
var selectedNodeID = workflowDialogContent.find(idSelector).val();
lookupTreeViewDialog.lookupTreeWidget('setSelectedNode', '#' + selectedNodeID);
lookupTreeViewDialog.lookupTreeWidget('saveCookie');
}).lookupTreeWidget();
lookupTreeWidget('onNodeDblClick', function (node) {
if (openDialog != null) {
lookupTreeWidget('saveCookie');
openDialog.data('result', { id: node.id, name: node.name });
openDialog.dialog('close');
}
});
}
//Called like so
this.buildGenericLookupTreeDialog(TemplateLookupTree, 'Select Template', '#DeviceTemplateID', '#DeviceTemplateName');
现在,这段代码立即抛出一个错误——TemplateLookupTree not defined。除非我实际初始化它(例如lookupTreeViewDialog.TemplateLookupTree()),否则我似乎无法通过其名称引用小部件;
如果我在传递到 buildGenericLookupTree 之前初始化 TemplateLookupTree - 每当使用 lookupTreeWidget 时都会收到错误,就像函数一样。
有关如何干燥此代码的任何建议?