I would like to use the Office Add-in technology to give to a Word document the Model-View-Controller logic.
In my scenario, the user should be able to create a new Word document, activate the Add-in and press a button inside the add-in to add a textbox field to the document. The field should display a number coming from the database: when the user updates that number and press save, the number should be written back to database. The next time the Word document is opened, the number should be refreshed, in order to display an updated value.
What I would like to know is whether the Add-in technology can be used (with binding support maybe?) or it is still in experimental stage. I'm having trouble trying to understand the best way to build a compact OOXML that simply represents my textbox: the method getSelectedDataAsync outputs a very complex document, it can't be the smarter way to describe a single-light-basic-poor-naked-textbox field! And how to set the binding to a custom XML? Where should that XML be placed? Inside the document? I looked at the samples provided on GitHub by Microsoft but they aren't so clear, since in many cases they're based on existing Word documents, which already have the necessary data and fields.
Definitely! The scenario you describe is actually one of the key types of add-in that the platform was originally designed for. The key element is a JavaScript object that we call a "Binding" that keeps track of a content control in the document, and there's no OXML or custom XML required.
The API is capable of adding a content control (similar to a text box) directly: call the Bindings.addFromSelectionAsync method.
function addNewField(fieldName){
Office.context.document.bindings.addFromSelectionAsync("text",
{ id: fieldName },
function (asyncResult){
displayNumberFromDatabase(asyncResult.value);
}
}
Also register for two event handlers so that you receive notifications when the user selects or modifies the text inside those content controls. The relevant events in this case are BindingSelectionChanged and BindingDataChanged, respectively.
Office.context.document.addHandlerAsync("bindingDataChanged", whenBindingDataChanged);
Office.context.document.addHandlerAsync("bindingSelectionChanged", whenBindingSelected);
When these events are triggered, you'll want to read the content. You can do that with the Binding.getDataAsync method.
function whenBindingDataChanged(eventArgs){
eventArgs.binding.getDataAsync(function(asyncResult){
setValueToDatabaseAsync(eventArgs.binding.id,asyncResult.value);
// you need to implement setValueToDatabaseAsync
});
}
And finally, to modify the contents of the Binding yourself to write the initial value, use the Binding.setDataAsync method.
function displayNumberFromDatabase(myBinding){
getValueFromDatabaseAsync(myBinding.id, function(value){
myBinding.setDataAsync(value);
});
// you need to implement getValueFromDatabaseAsync
}
-Michael Saunders, PM for Office add-ins