Monday, September 26, 2022

JavaScript Kendo Window as Dialog (async/await)

	
	// This function will add following methods in kendo Window
	//		openAsync()		opens the window asynchronously, true = OK, false = Cancel
	//		closeOk()		call this method on "OK" button click
	//		closeCancel()		call this method on "Cancel" button click
	//	IMPORTANT: kendoWindow paramter must be a kendow window
	//				e.g. addOpenAsyncInKendoWindow($("#popup").data("kendowWindow"));
    
	function addOpenAsyncInKendoWindow(kendoWindow) {
  		if (!kendoWindow.openAsync) {
			kendoWindow.bind("deactivate", () => {
      				if (kendoWindow.dispatchClosePopupCall)
        				kendoWindow.dispatchClosePopupCall(kendoWindow.asyncDialogResult);
			});
    			kendoWindow.getResponseAsync = async () => {
      				return (new Promise(resolve => kendowWindow.dispatchClosePopupCall = resolve)).then((data) => { kendowWindow.dispatchClosePopupCall = null; return data; });
			};  
    			kendoWindow.openAsync = async () => {
      				kendoWindow.center();
      				kendoWindow.open();
      				return await kendowWindow.getResponseAsync();
			};
    			kendoWindow.closeOk = () => {
      				kendoWindow.asyncDialogResult = true;
      				kendoWindow.close();
			};
    			kendoWindow.closeCancel = () => {
      				kendoWindow.asyncDialogResult = false;
      				kendoWindow.close();
			};
		}
	}
    
	// Example Usage
	$("#btnOpenPopup").on("click", async e => {
		e.preventDefault();
		const kp = $("#popup").data("kendoWindow");
		addOpenAsyncInKendowWindow(kp);
		const dialogResult = await kp.openAsync();
		if (dialogResult)
			alert("Ok was clicked");
		else
			alert("Cancel was clicked");
	});
    
	$("#btnOk").on("click", e => {
		e.preventDefault();
		const kp = $("#popup").data("kendoWindow");
		kp.closeOk();
	});
	$("#btnCancel").on("click", e => {
		e.preventDefault();
		const kp = $("#popup").data("kendoWindow");
		kp.closeCancel();
	});
JsFiddle Demo

No comments: