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);
};
};
}();
Excusing my use of JQuery mobile for the show/hide this is how I solved it after reading other answers.
By caching 'this' which is bound to the vm of the element being initially clicked on / contextmenu'd and the arguments of the function, you can use Function.apply in order to delegate the click.
This may cause issues where the original click handlers could inspect the event, and see it differs from a click event, but that could be solved with some minor refactoring.
<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 is run immediately, and returns a function that will be called when clicked.