ViewModel で定義された成功またはエラー メッセージを表示するためのコールバックをサポートする TypeScript バインディングが必要な場合:
import * as Clipboard from 'clipboard'
import * as ko from 'knockout';
/**
* Clipboard binding parameters.
*/
interface BindingContext {
/**
* Optional callback function which is executed on copy success - e.g show a success message
*/
successCallback: Function;
/**
* Optional callback function which is executed on copy error - e.g show an error message
*/
errorCallback: Function;
/**
* Optional args for the callback function
*/
args: Array<any>;
}
/**
* A binding handler for ClipboardJS
*/
class ClipboardBinding implements KnockoutBindingHandler {
init(element: Element, valueAccessor: () => BindingContext, allBindings: KnockoutAllBindingsAccessor, viewModel: any) {
const params = ko.unwrap(valueAccessor());
const successCallback = params.successCallback ? params.successCallback : null;
const errorCallback = params.successCallback ? params.successCallback : null;
const args = params.args ? params.args : [];
// init clipboard
const clipboard = new Clipboard(element);
// register success callback
if (typeof successCallback === 'function') {
clipboard.on('success', function (e) {
console.debug('Clipboard event:', e);
successCallback.apply(viewModel, args);
});
}
// register error callback
if (typeof errorCallback === 'function') {
clipboard.on('error', function (e) {
console.debug('Clipboard event:', e);
errorCallback.apply(viewModel, args);
});
}
}
}
export default new ClipboardBinding();
HTML:
<button class="btn btn-primary" data-bind="
clipboard: {
successCallback: $component.showCopySuccessMessage,
errorCallback: $component.showCopyErrorMessage
},
attr: {
'data-clipboard-text': 'Text to copy'
}">Copy to Clipboard</button>