Зарегистрировать прослушиватель событий при инициализации Office Addin (Excel) - PullRequest
1 голос
/ 11 июля 2019

Я хотел бы зарегистрировать прослушиватель событий, скажем, прослушиватель событий, когда рабочий лист изменился.Но слушатель должен автоматически регистрироваться, когда в офис инициализируется надстройка.Я знал, что при открытии панели задач вы можете зарегистрировать слушателя, но это не мой случай.На самом деле я пытался зарегистрировать прослушиватель событий при загрузке файла функции и не уверен, что это правильный путь.Буду признателен за любые предложения, как можно достичь этого решения, если это возможно.

Вот пример файла функции.

HTML

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

    <!-- Office JavaScript API -->
    <script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.debug.js"></script>

    <script type="text/javascript" src="../function-file.js"></script>
</head>

<body>
  <!-- NOTE: The body is empty on purpose. Since function in function-file.js are
       invoked via a button, there is no UI to render. -->
</body>

</html>

Файл машинописного текста

(() => {
  // The initialize function must be run each time a new page is loaded
  Office.initialize = () => {
    $(document).ready(function () {
      registerWorksheetChangedHandler()
      /* the rest of your code here */
    })
  };

  // Add any ui-less function here
})();

//Worksheet changed cell events
function registerWorksheetChangedHandler() {
  Excel.run(function (context) {
    var worksheet = context.workbook.worksheets.getActiveWorksheet()
    worksheet.onChanged.add(handleWorksheetChanged);

    return context.sync()
        .then(function () {
            console.log("Event handler successfully registered for onWorksheetChanged event in the worksheet.");
        });
}).catch(error => console.log("Error: " + error));
}

function handleWorksheetChanged(event)
{
  return Excel.run(function(context){
        return context.sync()
            .then(function() {
              console.log("Change type of event: " + event.changeType);
              console.log("Address of event: " + event.address);
              console.log("Source of event: " + event.source);
    }).catch(error => console.log("Error: " + error));
  })
}

Манифест

<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp
          xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
          xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides"
          xsi:type="TaskPaneApp">

  <!-- Begin Basic Settings: Add-in metadata, used for all versions of Office unless override provided. -->

  <!-- IMPORTANT! Id must be unique for your add-in, if you reuse this manifest ensure that you change this id to a new GUID. -->
  <Id>edcf304e-2101-4a0f-8306-7b34608f886a</Id>

  <!--Version. Updates from the store only get triggered if there is a version change. -->
  <Version>1.0.0.0</Version>
  <ProviderName>CSSoft a.s.</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <!-- The display name of your add-in. Used on the store and various places of the Office UI such as the add-ins dialog. -->
  <DisplayName DefaultValue="CSSoft Office Addin" />
  <Description DefaultValue="CSSoft Office Addin"/>

  <!-- Icon for your add-in. Used on installation screens and the add-ins dialog. -->
  <IconUrl DefaultValue="https://localhost:3000/assets/icon-32.png" />
  <HighResolutionIconUrl DefaultValue="https://localhost:3000/assets/icon-80.png"/>

  <!--If you plan to submit this add-in to the Office Store, uncomment the SupportUrl element below-->
  <!--<SupportUrl DefaultValue="[Insert the URL of a page that provides support information for the app]">-->

  <!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
  <AppDomains>
    <AppDomain>AppDomain1</AppDomain>
    <AppDomain>AppDomain2</AppDomain>
    <AppDomain>AppDomain3</AppDomain>
  </AppDomains>
  <!--End Basic Settings. -->

  <!--Begin TaskPane Mode integration. This section is used if there are no VersionOverrides or if the Office client version does not support add-in commands. -->
  <Hosts>
    <Host Name="Workbook" />
  </Hosts>
  <DefaultSettings>
    <SourceLocation DefaultValue="https://localhost:3000/index.html" />
  </DefaultSettings>
  <!-- End TaskPane Mode integration.  -->

  <Permissions>ReadWriteDocument</Permissions>

  <!-- Begin Add-in Commands Mode integration. -->
  <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">

    <!-- The Hosts node is required. -->
    <Hosts>
      <!-- Each host can have a different set of commands. -->
      <!-- Excel host is Workbook, Word host is Document, and PowerPoint host is Presentation. -->
      <!-- Make sure the hosts you override match the hosts declared in the top section of the manifest. -->
      <Host xsi:type="Workbook">
        <!-- Form factor. Currently only DesktopFormFactor is supported. -->
        <DesktopFormFactor>
          <!--"This code enables a customizable message to be displayed when the add-in is loaded successfully upon individual install."-->
          <GetStarted>
            <!-- Title of the Getting Started callout. resid points to a ShortString resource -->
            <Title resid="CSSoft.GetStarted.Title"/>

            <!-- Description of the Getting Started callout. resid points to a LongString resource -->
            <Description resid="CSSoft.GetStarted.Description"/>

            <!-- Point to a url resource which details how the add-in should be used. -->
            <LearnMoreUrl resid="CSSoft.GetStarted.LearnMoreUrl"/>
          </GetStarted>
          <!-- Function file is a HTML page that includes the JavaScript where functions for ExecuteAction will be called.
            Think of the FunctionFile as the code behind ExecuteFunction. -->
          <FunctionFile resid="CSSoft.DesktopFunctionFile.Url" />

          <!-- PrimaryCommandSurface is the main Office Ribbon. -->
          <ExtensionPoint xsi:type="PrimaryCommandSurface">
            <!-- Use OfficeTab to extend an existing Tab. Use CustomTab to create a new tab. -->
             <!-- <OfficeTab id="TabHome"> -->
             <CustomTab id="CSSoft.CustomTab">
              <!-- Ensure you provide a unique id for the group. Recommendation for any IDs is to namespace using your company name. -->
              <Group id="CSSoft.Group">
                <!-- Label for your group. resid must point to a ShortString resource. -->
                <Label resid="CSSoft.GroupLabel" />
                <!-- Icons. Required sizes 16,32,80, optional 20, 24, 40, 48, 64. Strongly recommended to provide all sizes for great UX. -->
                <!-- Use PNG icons. All URLs on the resources section must use HTTPS. -->
                <Icon>
                  <bt:Image size="16" resid="CSSoft.tpicon_16x16" />
                  <bt:Image size="32" resid="CSSoft.tpicon_32x32" />
                  <bt:Image size="80" resid="CSSoft.tpicon_80x80" />
                </Icon>
                <!-- Menu example -->
                <Control xsi:type="Button" id="CSSoft.Menu">
                  <Label resid="CSSoft.Menu.Label" />
                  <Tooltip resid="CSSoft.Menu.Tooltip" />
                  <Supertip>
                    <Title resid="CSSoft.Menu.Label" />
                    <Description resid="CSSoft.Menu.Tooltip" />
                  </Supertip>
                 <Icon>
                    <bt:Image size="16" resid="CSSoft.menu_16x16" />
                    <bt:Image size="32" resid="CSSoft.menu_32x32" />
                    <bt:Image size="80" resid="CSSoft.menu_80x80" />
                  </Icon>                
                  <Action xsi:type="ShowTaskpane">
                    <TaskpaneId>CSSoftMenuTaskPaneID</TaskpaneId>
                    <SourceLocation resid="CSSoft.Taskpane.Url" />
                  </Action>
                </Control>
              </Group>
             <!--</OfficeTab>-->
            <Label resid="CSSoft.CustomTab.Label" />
            </CustomTab>
          </ExtensionPoint>
        </DesktopFormFactor>
      </Host>
    </Hosts>

    <!-- You can use resources across hosts and form factors. -->
    <Resources>
      <bt:Images>
        <bt:Image id="CSSoft.tpicon_16x16" DefaultValue="https://localhost:3000/assets/icon-16.png" />
        <bt:Image id="CSSoft.tpicon_32x32" DefaultValue="https://localhost:3000/assets/icon-32.png" />
        <bt:Image id="CSSoft.tpicon_80x80" DefaultValue="https://localhost:3000/assets/icon-80.png" />
        <bt:Image id="CSSoft.menu_16x16" DefaultValue="https://localhost:3000/assets/menu_16x16.png" />
        <bt:Image id="CSSoft.menu_32x32" DefaultValue="https://localhost:3000/assets/menu_32x32.png" />
        <bt:Image id="CSSoft.menu_80x80" DefaultValue="https://localhost:3000/assets/menu_80x80.png" />
      </bt:Images>
      <bt:Urls>
        <bt:Url id="CSSoft.Taskpane.Url" DefaultValue="https://localhost:3000/index.html" />
        <bt:Url id="CSSoft.GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812" />
        <bt:Url id="CSSoft.DesktopFunctionFile.Url" DefaultValue="https://localhost:3000/function-file/function-file.html" />
      </bt:Urls>
      <!-- ShortStrings max characters==125. -->
      <bt:ShortStrings>
        <bt:String id="CSSoft.TaskpaneButton.Label" DefaultValue="Show Taskpane" />
        <bt:String id="CSSoft.GroupLabel" DefaultValue="Menu" />
        <bt:String id="CSSoft.GetStarted.Title" DefaultValue="Get started with your sample add-in!" />
        <bt:String id="CSSoft.CustomTab.Label" DefaultValue="CSSoft"/>
        <bt:String id="CSSoft.Menu.Label" DefaultValue="Go Menu"/>
      </bt:ShortStrings>
      <!-- LongStrings max characters==250. -->
      <bt:LongStrings>
        <bt:String id="CSSoft.TaskpaneButton.Tooltip" DefaultValue="Click to Show a Taskpane" />
        <bt:String id="CSSoft.GetStarted.Description" DefaultValue="CSSoft add-in loaded succesfully. Go to the CSSoft tab and click the 'Go Menu' button to get started." />
        <bt:String id="CSSoft.Menu.Tooltip" DefaultValue="Access into the main menu" />
      </bt:LongStrings>
    </Resources>
  </VersionOverrides>
  <!-- End Add-in Commands Mode integration. -->

</OfficeApp>
...