I have the following TypeScript defining a KnockoutJS binding handler for a clickable element on my view:
module MyModule {
export interface ICopyButtonParams {
dataUrl: string;
}
ko.bindingHandlers.copyButton = {
init: (element: HTMLElement, valueAccessor: () => ICopyButtonParams) => {
var options: any = ko.utils.unwrapObservable(valueAccessor());
if (!options.dataUrl) {
return;
}
new Clipboard(element, {
text: () => {
var clipboardData: string;
$.ajax({
url: options.dataUrl,
type: "GET",
contentType: "application/json",
cache: false,
async: false,
success: (result: SubmitResult) => {
clipboardData = result.Data;
}
});
return clipboardData;
}
});
}
};
}
What this binding handler does is it turns the clickable element into a Clipboard.JS enabled element that stores a string in the clipboard when clicked. In my case, I want to make use of Clipboard.JS's dynamic text functionality whereby you pass a function into the Clipboard constructor that returns the text you want to store in the clipboard. Inside this function, I want to make a call to an API that returns the text to store.
Because of the nature of this architecture, I am not able to use a standard ajax call with a success callback as that would mean that the clipboard text would not be resolved in time.
As a stopgap remedy, you will notice in my code that I have made my ajax call asynchronous (bad, I know). As the 'async' flag is deprecated from JQuery 1.8 onward, I am trying to think of an alternative approach.
Any ideas?