Search code examples
javascriptjqueryhtmlknockout.jszclip

Trying to use ZClip within Knockout


I am trying to create a website with dynamically loaded text, using Knockoutjs, that I want the user to be able to click on and have it copied to their clipboard. For the copy to clipboard functionality I'm using Zclip and I have it working when the text is statically loaded.

In my ViewModel, I have a function copyFunction that looks like this:

self.copyFunction = function(html) {
    console.log(html);
    $('#copytext').zclip({
        path: "http://www.steamdev.com/zclip/js/ZeroClipboard.swf",
        copy: function() {
            return $('#copytext').text();
        }
    });
}

This is called anytime one of the items is clicked on the web-page.

And in my HTML I have this sort of content being dynamically generated for each item I have:

<div class="row" data-bind="foreach: itemList">
        <div class="col-xs-3 text-center">
            <a data-bind="click: $parent.copyFunction, text: text" href="#" id="copytext"></a>
        </div>
</div>

I know that my copyFunction isn't correct but I don't know what I need to do to get it working for me. Ideally, I would like to apply the ZClip to the <a> tag that calls it, but I have no clue how to accomplish this.

The only way I've used ZClip before is the most well-known example: setting up an id in your HTML and using a jQuery event handler. However, I can't get that to work either because I'm new to JS and I'm pretty sure that the id isn't fully loaded when my jQuery function is, and thus it doesn't link up to the DOM correctly.

If you could help me gain insight as to how I can get this working I would greatly appreciate it.


Solution

  • Solved my problem by passing in the event as a parameter to the function.

    Here is how the function looks now:

    self.copyFunction = function(html, event) {
        var target = event.target;
        $(target).zclip({
            path: "http://www.steamdev.com/zclip/js/ZeroClipboard.swf",
            copy: function() {
                return $(target).text();    
            }
        });
    }
    

    An additional quirk I'm having is the Zclip only works when I upload the website to my server, but not from my localhost. Does anybody have a clue as to why this could happen?