如何在回调函数中设置元素属性

时间:2015-08-11 19:46:02

标签: javascript polymer

我有这个“服务”元素,我想用函数getTree设置属性“bookmarks”,它带有一个回调函数。

我的问题是我没有看到如何从回调函数中找到属性,其中“this”未定义!!

<dom-module id="...">
    <style>
    :host {
      display: none;
    }
    </style>
  <script>
    Polymer({
      is: "bookmark-service",
      properties: {
        bookmarks: {
          type: Array,          
          value: function() { return [{title:"init"}]; } 
        }
      },
  created: function() {
     chrome.bookmarks.getTree(
        function(bookmarkTreeNodes) {
            this.bookmarks = bookmarkTreeNodes;
            console.log(this.localName + '#' + this.id + ' in getTree.');
         } ); 
    console.log(this.localName + '#' + this.id + ' was created');
    console.log("Bookmark: " + this.bookmarks[0].title + '.'); 
 },
...

3 个答案:

答案 0 :(得分:1)

您可以使用bind在回调函数中设置this

 chrome.bookmarks.getTree(
    function(bookmarkTreeNodes) {
        this.bookmarks = bookmarkTreeNodes;
        console.log(this.localName + '#' + this.id + ' in getTree.');
     }.bind(this) ); 

答案 1 :(得分:1)

您可以在致电this之前保存getTree的参考:

var that = this;
chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
  that.bookmarks = bookmarkTreeNodes;
  console.log(that.localName + '#' + that.id + ' in getTree.');
});

答案 2 :(得分:0)

这是我问题的一部分,我不想使用“绑定”,我担心这可能会带来副作用,看起来更复杂。

但另一个问题是getTree的异步性质。为此,我必须添加observer

此外,属性甚至不存在于“已创建”阶段,我不得不使用“ready”

所以这是几乎最终的结果:

   properties: {
       bookmarks: {
          type: Array,
          value: function() { return [{title:"init"}]; },
          observer: 'bookready'
        }
    },

  bookready: function(){
    console.log("Bookmark ready: " + this.bookmarks[0].title + '.'); 
  },

  ready: function() {
    var self = this;
    chrome.bookmarks.getTree(
        function(bookmarkTreeNodes) {
           self.bookmarks = bookmarkTreeNodes[0].children;
         } 
    ); 
    console.log(this.localName + '#' + this.id + ' was readied');
    console.log("Bookmark: " + this.bookmarks[0].title + '.'); 
 },