someGlobalNamespace.ContextMenuVM = new function () {
var self = this;
var piece = {};
var args = [];
self.show = function (data, event) {
piece = this;
args = arguments;
var posx = event.clientX + window.pageXOffset; //Left Position of Mouse Pointer
var posy = event.clientY + window.pageYOffset; //Top Position of Mouse Pointer
$('#ContextMenu').popup('open', {
x:posx,
y:posy,
positionTo:'origin'
});
};
self.clickHandler = function(fn){
return function(){
$('#ContextMenu').popup('close');
fn.apply(piece, args);
};
};
}();
原谅我使用 JQuery mobile 进行显示/隐藏,这是我在阅读其他答案后解决它的方法。
通过缓存绑定到最初单击/上下文菜单的元素的 vm 和函数参数的“this”,您可以使用 Function.apply 来委托单击。
这可能会导致原始点击处理程序可以检查事件并看到它与点击事件不同的问题,但这可以通过一些小的重构来解决。
<div id="ContextMenu" class="pieceContextMenu" data-role="popup" data-theme="c" data-dismissible="true">
<div class="contextMenuItem CIicon Delete" title="Delete" data-bind="click: clickHandler(cms.canvasAreaVM.deleteUniformPiece)"><i style="cursor: pointer;" class="fa fa-times"></i><span class="contextMenuItemText">Delete</span></div>
<div class="contextMenuItem CIicon Copy" title="Clone" data-bind="click: clickHandler(cms.canvasAreaVM.copyFormPiece)"><i class="fa fa-copy"></i><span class="contextMenuItemText">Clone</span></div>
<div class="contextMenuItem CIicon New" title="Add new child" data-bind="click: clickHandler(cms.addNewPieceVM.show)"><i class="fa fa-plus"></i><span class="contextMenuItemText">New</span></div>
<div class="contextMenuItem CIicon NewParent" title="Add new parent" data-bind="click: clickHandler(cms.canvasAreaVM.newParentFormPiece)"><i class="fa fa-plus-square"></i><span class="contextMenuItemText">New Parent</span></div>
<div class="contextMenuItem CIicon CopyClip" title="Copy to the clipboard" data-bind="click: clickHandler(cms.canvasAreaVM.copyFormPieceToClipboard)"><i class="fa fa-clipboard"></i><span class="contextMenuItemText">Copy</span></div>
</div>
clickHandler 立即运行,并返回单击时将调用的函数。