Data binding 聚合物:在ajax响应后评估表达

Data binding 聚合物:在ajax响应后评估表达,data-binding,polymer,Data Binding,Polymer,我有自定义的聚合物组件,将加载整个应用程序的翻译。代码如下: <link rel="import" href="../polymer/polymer-expressions/polymer-expressions.html"> <link rel="import" href="../polymer/core-ajax/core-ajax.html"> <polymer-element name="nz-i18n" hidden> <script ty

我有自定义的聚合物组件,将加载整个应用程序的翻译。代码如下:

<link rel="import" href="../polymer/polymer-expressions/polymer-expressions.html">
<link rel="import" href="../polymer/core-ajax/core-ajax.html">
<polymer-element name="nz-i18n" hidden>
  <script type="text/javascript">
      Polymer('nz-i18n', {

          /**
           * our messages container
           */
          messages: {},

          /**
           * what loading is in progress
           */
          loading: {},

          created: function() {
              var self = this;
              // create new expression, to be used for translate method
              PolymerExpressions.prototype.$$ = function(key, params) {
                  // IMPORTANT !!! the scope here is the element we call this function from
                  // set this element as parent of the translator
                  self.parent = this;
                  // get translation
                  return self.translateMessage(key, params);
              };

              // restore loaded messages from local storage
              //this.restoreFromLocalStorage();
          },

          /**
           * Load messages from local storage
           */
          restoreFromLocalStorage: function() {
              // check if we have translations already loaded
              try {
                  if (translations = localStorage.getItem('nz-messages')) {
                      // convert JSON string representation to object
                      this.messages = JSON.parse(translations);
                      return true;
                  }
              } catch (e) {
                  // nothing to do
                  // we will load translations on demand
              }
          },

          /**
           * Translate message by given key and additional parameters
           *
           * IMPORTANT !!!do not use translate as the method name
           * there is such a property in the element
           *
           * @param key - key to be translated
           * @param params - additional parameters
           */
          translateMessage: function(key, params) {
              // set default parameters if not defined
              if (!params || params == 'undefined') {
                  var params = {};
              }
              if (!params.module) {
                  params.module = 'System';
              }

              var msg;
              if (this.messages[params.module]) {
                  // module messages are already loaded
                  try {
                      // try to get translation
                      msg = this.messages[params.module].messages[key] || key;
                      // key with multiple forms has been provided
                      if (typeof(msg) == "object") {
                          if (params.n != '' && params.n != 'undefined') {
                              //get index if the translation in function of the rules 
                               eval('idx = ' + this.messages[params.module].pluralRules.replace('n', params.n) + ';');
                              msg = msg[idx] || key;
                          } else {
                              msg = msg[0];
                          }
                      }
                  } catch (e) {
                      //no translation - return the key
                      msg = key;
                  }
              } else {
                  // module messages are not loaded
                  // start loading
                  this.loadTranslations(params.module);
                  // this will be processed very customly
                  msg = '';
              }

              return msg;
          },

          /**
           * Load messages for the module requested
           *
           * @param module - messages module
           * @param force - if we have to force loading even if
           *                messages for the module are already loaded
           */
          loadTranslations: function(module, force) {
              // set defaults
              if (!module) {
                  module = 'System';
              }
              // check if translations for this module are loaded
              // or if loading is in progress
              if (!this.loading[module] && (force || !this.messages[module])) {
                  // noooooooo - we will load them
                  this.loading[module] = true;
                  // create ajax request
                  ajax = document.createElement('core-ajax');
                  ajax.auto = true;
                  ajax.method = 'GET';
                  ajax.handleAs = 'json';
                  ajax.headers = {
                      "Accept": "application/json",
                      "Content-type": "application/json"
                  };
                  ajax.url = window.basePath + 'api/translations';
                  ajax.params = {"module": module};
                  // register event listeners for the response and post response processing
                  ajax.addEventListener('core-response', this.handleResponse);
                  ajax.parent = this;
                  // do not uncomment this - http://xhr.spec.whatwg.org/
                  //ajax.xhrArgs = {sync: true};
              }
          },

          /**
           * Process messages loading request
           */
          handleResponse: function() {
              // IMPORTANT !!!! core-ajax scope is here
              if (this.response) {
                  for (module in this.response) {
                      // add current response to the translations
                      this.parent.messages[module] = this.response[module];
                      // remove loading flag for this module messages
                      delete this.parent.loading[module];
                  }
                  // set translations in local storage
                  localStorage.setItem('nz-messages', JSON.stringify(this.parent.messages));
              }
          }
      });
  </script>
</polymer-element>

聚合物('nz-i18n'{
/**
*我们的消息容器
*/
消息:{},
/**
*正在进行什么加载
*/
正在加载:{},
已创建:函数(){
var self=这个;
//创建新表达式,用于转换方法
PolymerExpressions.prototype.$$=函数(键,参数){
//重要提示!!!这里的作用域是我们从中调用此函数的元素
//将此元素设置为转换器的父元素
self.parent=this;
//得到翻译
返回self.translateMessage(键,参数);
};
//从本地存储还原加载的邮件
//这是restoreFromLocalStorage();
},
/**
*从本地存储器加载消息
*/
restoreFromLocalStorage:函数(){
//检查我们是否已经加载了翻译
试一试{
if(translations=localStorage.getItem('nz-messages')){
//将JSON字符串表示转换为对象
this.messages=JSON.parse(翻译);
返回true;
}
}捕获(e){
//无事可做
//我们将根据需要加载翻译
}
},
/**
*按给定的键和附加参数翻译消息
*
*重要提示!!!不要将translate用作方法名
*元素中有这样一个属性
*
*@param key-要翻译的密钥
*@param params-其他参数
*/
translateMessage:函数(键、参数){
//如果未定义,则设置默认参数
如果(!params | | params==‘未定义’){
var params={};
}
如果(!参数模块){
params.module='System';
}
var-msg;
if(此消息[参数模块]){
//模块消息已加载
试一试{
//争取翻译
msg=this.messages[params.module].messages[key]| | key;
//已提供具有多种形式的密钥
if(typeof(msg)=“对象”){
if(params.n!=''&¶ms.n!='未定义'){
//如果在规则的作用下进行翻译,则获取索引
eval('idx='+this.messages[params.module].pluralRules.replace('n',params.n)+';');
msg=msg[idx]| |键;
}否则{
msg=msg[0];
}
}
}捕获(e){
//无翻译-返回密钥
msg=键;
}
}否则{
//未加载模块消息
//开始加载
此.loadTranslations(参数模块);
//这将按惯例进行处理
味精='';
}
返回味精;
},
/**
*为请求的模块加载消息
*
*@param模块-消息模块
*@param force-如果我们必须强制加载,即使
*模块的消息已加载
*/
载荷转换:功能(模块、力){
//设置默认值
如果(!模块){
模块=‘系统’;
}
//检查是否加载了此模块的翻译
//或者如果正在加载
如果(!this.loading[module]&&(force | |!this.messages[module])){
//不,我们会把它们装进去
此。加载[模块]=真;
//创建ajax请求
ajax=document.createElement('core-ajax');
ajax.auto=true;
方法='GET';
ajax.handleAs='json';
ajax.headers={
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
};
ajax.url=window.basePath+'api/translations';
ajax.params={“模块”:模块};
//为响应和响应后处理注册事件侦听器
addEventListener('core-response',this.handleResponse);
ajax.parent=this;
//请勿取消对以下内容的注释-http://xhr.spec.whatwg.org/
//ajax.xhrags={sync:true};
}
},
/**
*处理消息加载请求
*/
HandlerResponse:function(){
//重要!!!!这里是ajax的核心范围
如果(本.答复){
for(此.response中的模块){
//将当前响应添加到翻译
this.parent.messages[module]=this.response[module];
//删除此模块消息的加载标志
删除此.parent.loading[模块];
}
//在本地存储中设置翻译
setItem('nz-messages',JSON.stringify(this.parent.messages));
}
}
});
我还有另一个元素将用作框架集和wil
<link href="../../polymer/core-header-panel/core-header-panel.html" rel="import">
<link href="../../polymer/core-toolbar/core-toolbar.html" rel="import">

<polymer-element name="nz-frameset">
  <template>
    <link href="nz-frameset.css" rel="stylesheet">
    <core-header-panel flex>
      <!-- HEADER -->
      <core-toolbar justify="between">
        <img id="logo" src="../../images/logo.png" />
        <div id="title">{{ $$('header_title') }}</div>
      </core-toolbar>
      <!-- CONTENT -->
      <div class="content">{{ $$('num', {n: 4}) }}</div>
    </core-header-panel>
    <!-- FOOTER -->
    <core-toolbar bottomJustify="around">
      <footer class="bottom">
        {{ $('footer') }}
      </footer>
    </core-toolbar>
  </template>

  <script type="text/javascript">
      Polymer('nz-frameset', {
          ready: function() {

          },
      });
  </script
</polymer-element>
<body fullbleed vertical layout unresolved>
  <!-- INITIALIZE TRANSLATOR -->
  <nz-i18n></nz-i18n>
  <!-- LOAD FRAMESET -->
  <nz-frameset flex vertical layout></nz-frameset>
</body>
<div id="title">{{ n_translate | $$('header_title') }}</div>
this.fire("translationChanged");
this.addEventListener("translationChanged", function() {
 this.n_translate = new Date(); // some changed value
});