Alrighty, thanks @devspec for your initial answer. I built on it in some crucial ways:
so my final binding handler is:
ko.bindingHandlers.clipboard = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
var options = ko.unwrap(valueAccessor());
if(options.textComputed) {
options.text = function(nodeToIgnore) { return options.textComputed(); };
}
if(options.onmodal) {
options.container = element;
}
var cboard = new Clipboard(element, options);
if(options.success) {
cboard.on('success', options.success);
}
if(options.error) {
cboard.on('error', options.error);
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
// This will be called when the element is removed by Knockout or
// if some other part of your code calls ko.removeNode(element)
cboard.destroy();
});
},
}
And an example of usage is:
The Html:
<a href="#" data-bind="clipboard: { onmodal: true, textComputed: command, success: function(event) { copyCommandResult(true, event); },
error: function(event) { copyCommandResult(false, event); }}"><small
data-bind="text: clipboardLink ">copy to clipboard</small></a>
on the view model command is a computed, if it was a function that returned a string (without an argument) you could use the text attribute only
And the copyCommandResult is simply:
self.copyCommandResult = function(success, e) {
// console.log("Copy to clipboard success? " + success)
// console.info('Action:', e.action);
// console.info('Text:', e.text);
// console.info('Trigger:', e.trigger);
if(success) {
self.clipboardLink("Copied successfully!");
} else {
self.clipboardLink("Could not copy to clipboard");
}
setTimeout(function(){ self.clipboardLink(DEFAULT_CLIPBOARD_LINK_TEXT); }, 3000);
}