简体   繁体   中英

How to set an element property from within a callback function

I have this "service" element where I would like to set the property "bookmarks" with the function getTree, which takes a callback function.

My problem is that I don't see how I could reach the property from within the callback function where "this" is undefined!!

<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 + '.'); 
 },
...

You can use bind to set this in your callback function.

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

You could save a reference for this before calling getTree :

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

That was a part of my problem and I prefer not to use "bind" which I fear may have side effects with this and looks more complicated.

But another problem, was the asynchronous nature of getTree. For this, I had to add an observer .

Also, the properties doesn't even exist in "created" phase, I had to use "ready"

So here is the almost final result:

   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 + '.'); 
 },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM