Now add the following functions to the myofficeapp.js file like this:
// Add any initialization logic to this function.
Office.initialize = function (reason) {
// Checks for the DOM to load.
$(document).ready(function () {
$("#getDatabtn").click(function () { getData("selectedData"); });
// Checks if setSelectedDataAsync is supported and adds appropriate click handler
if (Office.context.document.setSelectedDataAsync) {
$("#setDatabtn").click(function () { setData("Sample data"); });
}
else {
$("#setDatabtn").remove();
}
});
}
// Writes data to current selection.
function setData(dataToInsert) {
Office.context.document.setSelectedDataAsync(dataToInsert);
}
// Reads data from current selection.
function getData(elementIdToUpdate) {
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
function (result) {
if (result.status == "succeeded") {
document.getElementById(elementIdToUpdate).value = result.value;
}
});
}
function writeToPage(text) {
document.getElementById('outputs').innerText = text;
}
function bindData() {
Office.context.document.bindings.addFromSelectionAsync("matrix", { id: 'bindingdata' },
function (asyncResult) {
if (asyncResult.status === "failed") {
writeToPage('Error: ' + asyncResult.error.message);
} else {
writeToPage('Added binding with type: ' + asyncResult.value.type + ' and id: ' +
asyncResult.value.id);
}
});
}
function readBoundData() {
Office.select("bindings#bindingdata").getDataAsync({ coercionType: "matrix" },
function (asyncResult) {
if (asyncResult.status == "failed") {
writeToPage('Error: ' + asyncResult.error.message);
} else {
writeToPage('Selected data: ' + asyncResult.value);
}
});
}
function addEvent() {
Office.select("bindings#bindingdata").addHandlerAsync("bindingDataChanged", myHandler, function (asyncResult) {
if (asyncResult.status == "failed") {
writeToPage('Error: ' + asyncResult.error.message);
} else {
writeToPage('Added event handler');
}
});
}
function myHandler(eventArgs) {
eventArgs.binding.getDataAsync({ coerciontype: "matrix" }, function (asyncResult) {
if (asyncResult.status == "failed") {
writeToPage('Error: ' + asyncResult.error.message);
} else {
writeToPage('Bound data: ' + asyncResult.value);
}
});
}
In this the code in the writecontent() function will call the document.setSelectedDataAsync function in order to write "Good morning world!!!!!" to the current cell when we will choose the Write
Content button. In his most of the functions are Asynchronous that's why their name ends with "Async".