(JavaScript API 1.3 for Office) Custom Properties GetItemOrNull

走远了吗. 提交于 2019-12-02 06:19:57

Thanks for asking this question.

Your code is correct except for one minor detail: All the *getItemOrNullObject methods do NOT return a JavaScript null, so your "if (!temp)" statement will not work as you expect. If you want to validate existence you need to call if(temp.isNullObject) instead.

Also a couple of suggestions:

  1. customProperties.add() semantics is that if the property does exist, it will be replaced. So, If you want to create or change the property you don't need to check if it exists or not. If you want to read its current value you do. This answers your 2nd question.
  2. I have a simplified and more efficient proposal for your code, if you are interested on loading a single property.

  Word.run(function (context) {
    var myProperty = context.document.properties.customProperties.getItemOrNullObject("X");
    context.load(myProperty);
    return context.sync()
      .then(function () {
        if (myProperty.isNullObject) {
          //this means the Custom Property does not exist....
          context.document.properties.customProperties.add("X", 1234);
          console.log("Property Created");
          return context.sync();
        }
        else
          console.log("The property already exists,  value:" + myProperty.value);
      })
  })
  .catch(function (e) {
      console.log(e.message);
    })

We will update the documentation as this seems to be confusing.

Thanks!

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