【问题标题】:Polymer: this.setAttribute() is not a function聚合物:this.setAttribute() 不是函数
【发布时间】:2016-10-18 14:16:18
【问题描述】:

所以我试图让一些 Polymer 数据绑定工作,但由于某种原因,下面的代码给了我一个 TypeError: this.setAttribute is not a function(…)

我尝试将this.setAttribute('display', 1); 替换为this.display = 1;,但这似乎也不起作用。

我做错了什么?

Polymer({
  is: 'unibz-club',

  properties: {
    display:{
      type: Number,
      notify: true,
      value: 0,
    }
  },
  ready: function() {
    this.setAttribute('display', 1);    //  <--not working
  }.bind(this),
};

【问题讨论】:

  • 嗯,需要注意的一点是,您在结束分号之前缺少了一个右括号。
  • 为什么要显式绑定“this”?我相信“就绪”方法已经有一个 this 上下文,它引用了正在实例化的 Polymer 对象。现在,您可能正在将上下文更改为窗口或包含关闭。
  • 对不起,括号在我的代码中是封闭的,但绑定“this”的提示做到了!你能解释一下我什么时候需要绑定“这个”,什么时候不需要?我似乎找不到一个好的解释...
  • 哦,非常感谢!

标签: javascript data-binding polymer


【解决方案1】:

'ready' 方法已经有一个 this 上下文,它引用正在实例化的 Polymer 对象。现在,您正在使用 .bind(this) 调用将上下文更改为窗口或包含闭包。

Polymer 库正在为您处理这个问题。它将在新创建的对象的上下文中调用“就绪”方法。

您通常会使用 .bind() 在回调方法和 then-able Promise 中定义 this 的上下文。当然还有其他用途,但在我的经验中这是最常见的。

function ImageLoader () {
    return this;
}

ImageLoader.prototype.load = function(path) {
    return ajaxService.get(path);    
};

function Gallery () {
    this.images = [];
    return this;
}

Gallery.prototype.init = function() {
    new ImageLoader().load('/photos/gallery').then(function(result) {
        this.images = result; 
    }.bind(this)); // <-- .bind(this) will set the context of `this` to the Gallery instance
};

var gallery = new Gallery();
gallery.init();

【讨论】:

  • 谢谢!这对我帮助很大!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2017-03-23
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
相关资源
最近更新 更多