How to implement OnEnter and OnExit event on ContentControl using Javascript API for Word 2016

痴心易碎 提交于 2021-02-19 02:21:41

问题


There are many contentcontrols in a document and I need to find out a way that the cursor is in which content control so that I will select that control and do the operation accordingly. I think by implementing onEnter and onExit events for contentcontrols , I can achieve it. But I don't know how to declare and invoke those eventhandlers in JavaScript api. Any help is really appreciated.


回答1:


You would need to use a combination of APIs to implement that functionality with the current API set:

  1. First add an event handler for the Document.selectionChanged event.
  2. Every time the event fires, get the Range object corresponding to the selection in the document, using the Document.getSelection() API.
  3. Check the range to see if there's a content control in it, using the Range.contentControls relationship.

-Michael (PM for add-ins)




回答2:


Good question! We do have an onEnter event for content controls (we call it binding.selectionChanged. We also have a binding.dataChanged event who gets triggered if the user changes the content and exits the content control

so an alternative solution to what Michael proposed is to create bindings for each content control in the document and then register for such events.

you can achieve this by: 1. traversing the content control collection.(use body.contentControls collection) 2. for each content control, grab or set the title and use it to create a binding by named item. check the bindings.addFromNamedItem method. 3. on the callBack make sure to subscribe to the selectionChanged (or DataChanged) for the binding. the create binding code and register to the events will look like this:

function CreateCCSelectionChangedEvent() {
        Office.context.document.bindings.addFromNamedItemAsync("TitleOfTheContentControl", { id: 'Binding01' }, function (result) {
            if (result.status == 'succeeded') {
                result.value.addHandlerAsync(Office.EventType.BindingSelectionChanged, handler);
            }
        });
       
    }

    function handler() {
       console.log("Event Triggered!");
    }

Hope this helps!



来源:https://stackoverflow.com/questions/36704444/how-to-implement-onenter-and-onexit-event-on-contentcontrol-using-javascript-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!