簡體   English   中英

如何讓 KnokoutJS 和 ClipboardJS 協同工作?

[英]How to make KnokoutJS and ClipboardJS work together?

我嘗試將來自 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>

使用 ClipboardJS:

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

但這不是抄襲。 我做錯了什么?

所以,也許有人需要:

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>

好的,感謝@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);

  }

如果有人需要一個 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>
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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM