如何为函数建立全局变量 - 聚合物

时间:2017-07-13 10:51:51

标签: javascript html polymer

我在这里搜索了一些文件,但我无法弄明白。

基本上我只想为这个特定文件全局设置一些变量(就像本地全局变量一样),所以我不需要为我使用的每个函数继续定义它们,因为它会变得相当长厌倦了。

任何建议都可以做到!

我知道在这样的情况下,在Polymer中很难做到全局变量和事情,但是我希望我能学会如何去做,因为它可以节省我很多时间和努力。

原创JS

Polymer({

  is: 'settings-page',

  properties: {
      response : {
          type : Object
      },
  },

  /* have iron pages show the saved state of each section to start with */
  ready: function () {
      this.selected = 'saved';
      this.selection = 'saved';
  },

  editDetails : function () {
      /*    click edit | open edit mode | edit icon disappears | save & cancel icons appear     */

      var editButton = this.$.editInfo;
      var saveButton = this.$.saveInfo;
      var cancelButton = this.$.clearInfo;

      saveButton.classList.add('show');
      cancelButton.classList.add('show');
      editButton.classList.add('hide');
  },

/* There are saveDetails and cancelDetails functions below doing 
    pretty much the same stuff. */

在看到网上示例后的JS

(function() {
    var data = {
            editInfo: this.$.editInfo,
            saveInfo: this.$.saveInfo,
            cancelInfo: this.$.clearInfo
    }

    Polymer({

      is: 'settings-page',

      properties: {
          response : {
              type : Object
          },
      },

      /* have iron pages show the saved state of each section to start with */
      ready: function () {
          this.selected = 'saved';
          this.selection = 'saved';
          this.data = data;
      },

      editDetails : function () {
          /*    click edit | open edit mode | edit icon disappears | save & cancel icons appear     */


          saveButton.classList.add('show');
          cancelButton.classList.add('show');
          editButton.classList.add('hide');
      },

 /* There are saveDetails and cancelDetails functions below doing 
    pretty much the same stuff. */

1 个答案:

答案 0 :(得分:1)

不幸的是,没有办法在聚合物中声明全局变量,你有两种方法。

在我看来,最好的方法是将变量声明为聚合物给出的属性字段。

properties: {
  response : {
      type : Object
  },
  editButton: {
      type: Object
  },
  //more declarations
},

ready: function () {
    this.editButton = this.$.editInfo;
    //more assignations
}

在你的情况下,我会直接使用this.$.editInfo,根据' KISS'而没有辅助变量。原理

第二种方式是如此丑陋但是对于定义全局变量,您可以使用窗口Object来设置变量。