knockout.js 如何使KnokoutJS和ClipboardJS一起工作?

n8ghc7c1  于 2022-11-10  发布在  其他
关注(0)|答案(4)|浏览(116)

我尝试从Knockout foreach复制一些信息到剪贴板:

<tbody data-bind="foreach: selections">
    <tr>
        <td>
            <a href="#" class="copy_btn" data-bind="attr: { 'data-clipboard-text' : name}"><i class="fa fa-copy"></i></a>
        </td>
    </tr>
</tbody>

使用剪贴板JS:

var btns = document.querySelectorAll('a.copy_btn');
var clipboard = new Clipboard(btns);

clipboard.on('success', function (e) {
    console.log(e);
});
clipboard.on('error', function (e) {
    console.log(e);
});

但这不是抄袭。我做错了什么?

ql3eal8s

ql3eal8s1#

也许有人需要:

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

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

mnemlml82#

好的,谢谢@devspec你最初的回答。我在一些重要的方面都是基于这个答案的:
所以我的最终绑定处理程序是:

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();
                    });
        },
}

下面是一个用法示例:
“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>

是一个计算的,如果它是一个返回字符串(不带参数)的函数,则只能使用text属性
而copyCommandResult则是简单的:

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);

  }
bvhaajcl

bvhaajcl3#

如果有人需要一个TypeScript绑定,它支持回调以显示在ViewModel中定义的成功或错误消息:

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

yvfmudvl4#

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);
}

相关问题