Skip to content Skip to sidebar Skip to footer

How To Make Knokoutjs And Clipboardjs Work Together?

I try to copy to clipboard some information from Knockout foreach:

Solution 1:

So, maybe somebody needs:

ko.bindingHandlers.clipboard = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var clipboard = newClipboard(element);
    }
};

and

<ahref="#"class="copy_btn"data-bind="clipboard, attr: { 'data-clipboard-text' : name, title: 'Copy to clipboard'}"><iclass="fa fa-copy"></i></a>

Solution 2:

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. herevar options = ko.unwrap(valueAccessor());
            if(options.textComputed) {
                options.text = function(nodeToIgnore) { return options.textComputed(); };
            }

            if(options.onmodal) {
                options.container = element;
            }

            var cboard = newClipboard(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:

<ahref="#"data-bind="clipboard: { onmodal: true, textComputed: command, success: function(event) { copyCommandResult(true, event); },
error: function(event) { copyCommandResult(false, event); }}"><smalldata-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);

  }

Solution 3:

In case somebody needs a TypeScript binding which supports callbacks for displaying success or error messages defined in your ViewModel:

import * as Clipboard from'clipboard'
import * as ko from'knockout';

/**
 * Clipboard binding parameters.
 */interfaceBindingContext {

    /**
     * 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
 */classClipboardBindingimplementsKnockoutBindingHandler {

    init(element: Element, valueAccessor: () => BindingContext, allBindings: KnockoutAllBindingsAccessor, viewModel: any) {
        constparams = ko.unwrap(valueAccessor());
        const successCallback = params.successCallback ? params.successCallback : null;
        const errorCallback = params.successCallback ? params.successCallback : null;
        const args = params.args ? params.args : [];

        // init clipboardconst clipboard = new Clipboard(element);

        // register success callbackif (typeof successCallback === 'function') {
            clipboard.on('success', function (e) {
                console.debug('Clipboard event:', e);
                successCallback.apply(viewModel, args);
            });
        }

        // register error callbackif (typeof errorCallback === 'function') {
            clipboard.on('error', function (e) {
                console.debug('Clipboard event:', e);
                errorCallback.apply(viewModel, args);
            });
        }
    }
}

export defaultnewClipboardBinding();

The 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>

Solution 4:

self.functionName = function(text) {
var input = document.body.appendChild(document.createElement("input"));
input.value = text;
input.focus();
input.select();
document.execCommand('copy');
input.parentNode.removeChild(input);
}

Post a Comment for "How To Make Knokoutjs And Clipboardjs Work Together?"