Reputation: 5550
I would like to add an event handler to the ranges or cells that a user select in a workbook: if the user selects another cell or range, some actions need to be undertaken systematically.
I am looking at this reference, but I don't know where to integrate the code into the whole add-in.
For instance, in my Home.html
, i have
<div id="content-main">
<div class = "padding" id="message"></div>
<div class="padding">
<button class="ms-Button" id="button">Click me!</button>
</div>
</div>
Here is Home.js
:
(function() {
"use strict";
Office.initialize = function(reason) {
$(document).ready(function() {
app.initialize();
$('#button').click(activateEventHandler);
});
};
function onBindingSelectionChanged(eventArgs) {
write(eventArgs.binding.id + " has been selected.");
}
function write(message) {
document.getElementById('message').innerText += message;
}
function activateEventHandler() {
Excel.run(function(ctx) {
var selectedRange = ctx.workbook.getSelectedRange();
selectedRange.addHandlerAsync(Office.EventType.BindingSelectionChanged, onBindingSelectionChanged);
return ctx.sync()
}).then(function() {
console.log("done");
}).catch(function(error) {
...
}
});
}
})();
I would expect the button activates the listener. Then, each time the user selects another cell or range, a message is systematically appended to the task pane. However, the above code raises an error:
Error: TypeError: selectedRange.addHandlerAsync is not a function
at the line selectedRange.addHandlerAsync(...
.
Actually, I am not even sure this code should be structured like that... Does anyone know how to modify the code to achieve my task?
Upvotes: 0
Views: 721
Reputation: 2668
The cause of the error is that you are trying to call the function addHandlerAsync on a Range object. But handlers can only be added to Binding objects or the Document object. Which one you choose depends on exactly what you want to accomplish. In your case I think you're not trying to listen for selections at specific ranges, but actually to listen for selections anywhere in the document. So you would actually use the DocumentSelectionChanged event:
(function() {
"use strict";
Office.initialize = function(reason) {
$(document).ready(function() {
app.initialize();
$('#button').click(activateEventHandler);
});
};
function onMySelectionChanged(eventArgs) {
write(eventArgs.binding.id + " has been selected.");
doStuffWithNewSelection();
}
function write(message) {
document.getElementById('message').innerText += message;
}
function activateEventHandler(){
Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, onMySelectionChanged);
}
function doStuffWithNewSelection() {
Excel.run(function(ctx) {
var selectedRange = ctx.workbook.getSelectedRange();
// do other stuff with the selection as you wish, like read and display
}).then(function() {
console.log("done");
}).catch(function(error) {
...
}
});
}
})();
Upvotes: 1