Bindings
This represents the bindings the add-in has within the document.
Creating the Binding
Office.context.document.bindings.AddFromNamedItemAsync(
'MyTableNamedRange',
Office.BindingType.Table,
{id:'MyUniqueBindingId'},
function(asyncResult) {
if (asyncResult.status !== Office.AsyncResultStatus.Suceeded)
{}
else
{
#disable the button that fires this code
$('my-unique-name').attr('disabled','disabled');
#enable the button for writing data
$('writing-data').remveattr('disabled');
#enable a button for reading data
$('reading-data').remveattr('disabled');
}
Writing Data
Reading Data
Selecting a range from the prompt will bind to that range */
Bind to the matrix in the document from prompt
Office.context.document.bindings.addFromPromptAsync(Office.BindingType.Matrix,
{ id: "MyMatrixBinding" },
function (asyncResult) {
if (asyncResult.status == "failed") {
showMessage("Action failed with error: " + asyncResult.error.message);
}
else {
showMessage("Added new binding with type: " + asyncResult.value.type +
" and id: " + asyncResult.value.id);
}
});
The next step is to bind to the range (matrix). Binding to a region in a document establishes a link between that region and the app that can be referenced later on. After a Binding object is created, you can retrieve it at any time, read and write data to the region of the document associated with it, and handle selection and data change events. This example demonstrates binding by displaying a prompt using the addFromPromptAsync method, which prompts the user to make a selection in the document and binds to that selection. Be aware that bindings can also be created based on current user selection (without displaying a prompt) and from existing named items in the document or spreadsheet. The example also shows how a binding ID can be specified when you create the binding. The binding ID, 'MyMatrixBinding', can then be used to retrieve the binding. The callback function returns an asyncResult object containing the binding object, which can be accessed by using the asyncResult.value property.
Click Run Code to add an event handler to the Matrix binding.
Then select different cells in the Matrix to trigger the event and read the current selected cell.
Get the binding and add an event handler to detect selection change events
Office.select("bindings#MyMatrixBinding", onBindingNotFound).
addHandlerAsync(Office.EventType.BindingSelectionChanged,
onBindingSelectionChanged,
function(AsyncResult){
showMessage("Event handler was added successfully!"+
" Change the matrix current selection to trigger the event");
});
//Trigger on selection change, get partial data from the matrix
function onBindingSelectionChanged(eventArgs) {
eventArgs.binding.getDataAsync({CoercionType: "matrix",
startRow:eventArgs.startRow,
startColumn:eventArgs.startColumn,
rowCount:1, columnCount:1},
function(asyncResult) {
if (asyncResult.status == "failed") {
showMessage("Action failed with error: " + asyncResult.error.message);
}
else{
showMessage(asyncResult.value[0].toString());
}
});
}
//Show error message in case the binding object wasn"t found
function onBindingNotFound(){
showMessage("The binding object was not found."+
" Please return to previous step to create the binding");
}
After binding to the matrix, the next step is to detect when a user changes selection in that range and then read the selected cell coordinates. This can be done by adding an event handler function to the binding to detect selection change events. Once the event is triggered, the event handler function, onBindingSelectionChanged(), is called and gets data from the binding using the Binding.getDataAsync method. By default, the getDataAsync method returns all the data contained in a text, matrix, or table binding. However, it is possible to get a partial set of the data by specifying the startRow, startColumn, rowCount and columnCount parameters of the method. The data is then returned by the asyncResult object and can be accessed through the value property.
This will create a binding to the table
Bind to the table in the document from user current selection
Office.context.document.bindings.addFromSelectionAsync("table",
{ id: "MyTableBinding" },
function (asyncResult) {
if (asyncResult.status == "failed") {
showMessage("Action failed with error: " + asyncResult.error.message);
}
else {
showMessage("Added new binding with type: " + asyncResult.value.type +
" and id: " + asyncResult.value.id);
}
});
The next step is to bind to the table. Unlike the basic writing and reading methods, binding to a region in a document establishes a link between that region and the app that can be referenced later on. After a Binding object is created, you can access it at any time, read and write data to the region of the document associated with it, and handle selection and data change events.
This example demonstrates binding to the user's current selection using the addFromSelectionAsync method. Be aware that bindings can also be created based on selection from a prompt (Excel only), and from existing named items in the document and spreadsheet. The example also shows how a binding ID can be specified ('MyTableBinding') when you create the binding. The binding ID can then be used to retrieve the binding. The callback function returns an asyncResult object containing the binding, which can be accessed using the asyncResult.value property.
Creating the row to update
var table = new Office.TableData();
table.rows = ["Seattle","WA"];
var rowToUpdate = 2;
//Getting the table binding and setting data in 3rd row.
Office.select("bindings#MyTableBinding", onBindingNotFound).setDataAsync(table,
{coercionType: "table",
startRow: rowToUpdate},
function(asyncResult) {
if (asyncResult.status == "failed") {
showMessage("Action failed with error: " + asyncResult.error.message);
}
else {
showMessage("Updated row number 3 with this data: " + table.rows);
}
});
//Show error message in case the binding object wasn"t found
function onBindingNotFound(){
showMessage("The binding object was not found. "+
"Please return to previous step to create the binding");
}
Now we can use the binding object created in the previous step to update the table content. The example shows how to retrieve the table binding based on its ID using the Office.select selector method and then calls the setDataAsync method to write data into the binding object, which will be reflected in the table associated with the binding. First, a TableData object containing one row, is created. The TableData object is then passed as the data parameter to the method along with a startRow parameter value to indicate the position in the table to replace with the supplied table. Be aware that the shape of the table used to update the binding must match the shape of the updated table in terms of the number of columns and rows. The callback function returns an asyncResult object containing the status of the performed operation.
Create a table with a single column
var populationTable = new Office.TableData();
populationTable.headers = [["Population"]];
populationTable.rows = [["1593659"],["416468"],["616627"],["645169"]];
//Finding the binding by its id
Office.context.document.bindings.getByIdAsync("MyTableBinding",
function(asyncResult){
if (asyncResult.status == "failed") {
showMessage("Action failed with error: " + asyncResult.error.message);
}
else {
//GetBindingById returns a binding object.
//If the binding object was found, add a column to it
asyncResult.value.addColumnsAsync(populationTable,
function(result){
if (result.status == "failed") {
showMessage("Action failed with error: " + result.error.message);
}
else {
showMessage("Successfully added Population column!");
}
});
}
});
In addition to updating existing data in the table, the table binding object can be used to add new columns and rows. The example shows how to retrieve the table binding based on its ID using the getById method exposed by the Bindings object. First, a TableData object containing a header and one column is created. Once the binding object is retrieved, the new table is passed as the data parameter to the addColumnsAsync method. Be aware, that just like updating table data, adding columns and rows requires that the shape of object added to the table matches the shape of the table (in this example, the new column created has the same number of rows as the table). The callback function returns an asyncResult object containing the status of the performed operation. Office.select selector method and then calls the setDataAsync method to write data into the binding object, which will reflect in the table.
© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext