2017-02-22 58 views
1

几天前我创建了this,其中我需要关于如何将自定义属性添加到所述文档的帮助。(适用于Office的JavaScript API 1.3)自定义属性GetItemOrNull

首先,我正在运行Word 1701(7766.2047)。


比方说,我有一个方法在其中我返回一个上述自定义属性。首先我会检查自定义属性是否已经创建。我会用一个简单的getItemOrNullObject(键),这样做..

  • 如果返回null,简单地创建并返回它
  • 否则返回它

这是我的理解是,我需要做一个返回context.sync()。然后为对象获取实际加载的数据?我做了太多的返回context.sync()调用什么?

Word.run(function(context) { 
 
    var customDocProps = context.document.properties.customProperties; 
 
    context.load(customDocProps); 
 
    return context.sync() 
 
    .then(function() { 
 
     var temp = customDocProps.getItemOrNullObject("X"); 
 
     return context.sync() 
 
     .then(function() { 
 
      if (!temp) { 
 
      context.document.properties.customProperties.add("X", 1234); 
 
      temp = customDocProps.getItemOrNullObject("X"); 
 
      return context.sync() 
 
       .then(function() { 
 
       return temp; 
 
       }); 
 
      } else { 
 
      return temp; 
 
      } 
 
     }); 
 
    }); 
 
});

下面的代码抛出我的 '的ReferenceError: '字' 是未定义' 在启动,但如果我调试它运行时,它打破

var customDocProps = context.document.properties.customProperties; context.load(customDocProps); return context.sync().{....}


还有一个问题。说我想更新我的自定义属性,会:

Word.run(function (context) { 
 
     context.document.properties.customProperties.add("X", 56789); 
 
     return context.sync(); 
 
    });

覆盖旧值与新的?

如果你读了这个答案,谢谢!任何帮助表示赞赏。 干杯!

回答

3

感谢您提出这个问题。

你的代码是除了一个小细节正确的:所有的* getItemOrNullObject方法做返回一个JavaScript无效,所以你的“如果(临时!)”语句也不会像您期望的工作。如果你想验证存在,你需要调用if(temp.isNullObject)来代替。

还提供了一些建议:

  1. customProperties.add()的语义是,如果属性不存在,它会被替换。所以,如果你想创建或更改属性,你不需要检查它是否存在。如果你想读你目前的价值。这回答你的第二个问题。
  2. 如果您对加载单个属性感兴趣,我为您的代码提供了一个简化且更高效的提案。

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); 
 
    })

,因为这似乎是混乱,我们将更新的文档。

谢谢!

+0

这是我的理解是Word.run()异步运行,所以如果我想保存它的返回值,我应该尝试使用一个回调。这可能与Word.run()? –

+0

如果要返回属性值仅返回什么是从我的样本myProperty.value。使用 –

+0

您的样品。当标签是空我总是context.sync后一般例外() 这是verbatum为你写的,所以我看不出有什么不对。我应该开一个新的问题吗? http://imgur.com/a/TKujx –