gpt4 book ai didi

javascript - 如何为函数建立全局变量 - Polymer

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:54 24 4
gpt4 key购买 nike

我已经搜索了这里的一些文档,但我不太明白。

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

任何建议都会很棒!

我知道在这种情况下,全局变量和其他事情在 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. */

最佳答案

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

我认为最好的方法是将变量声明到 polymer 给出的属性字段中。

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

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

在您的情况下,我将直接使用 this.$.editInfo,根据“KISS”原则,无需辅助变量。

第二种方法很丑陋,但是为了定义全局变量,您可以使用窗口对象来设置变量。

关于javascript - 如何为函数建立全局变量 - Polymer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45078519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com