Javascript 如何在回调函数中设置元素属性
我有一个“service”元素,我想用getTree函数设置属性“bookmarks”,它接受一个回调函数Javascript 如何在回调函数中设置元素属性,javascript,polymer,Javascript,Polymer,我有一个“service”元素,我想用getTree函数设置属性“bookmarks”,它接受一个回调函数 chrome.bookmarks.getTree( function(bookmarkTreeNodes) { this.bookmarks = bookmarkTreeNodes; console.log(this.localName + '#' + this.id + ' in getTree.'); }.bind(this) );
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
this.bookmarks = bookmarkTreeNodes;
console.log(this.localName + '#' + this.id + ' in getTree.');
}.bind(this) );
我的问题是,我不知道如何从未定义“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 + '.');
},
...
:主持人{
显示:无;
}
聚合物({
是:“书签服务”,
特性:{
书签:{
类型:数组,
值:函数(){return[{title:“init”}];}
}
},
已创建:函数(){
chrome.bookmarks.getTree(
函数(书签树节点){
this.bookmarks=bookmarkTreeNodes;
log(getTree中的this.localName+'#'+this.id+);
} );
console.log(this.localName+'#'+this.id+'已创建);
console.log(“Bookmark:+this.bookmarks[0].title+”);
},
...
您可以使用在回调函数中设置此
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
this.bookmarks = bookmarkTreeNodes;
console.log(this.localName + '#' + this.id + ' in getTree.');
}.bind(this) );
在调用getTree
之前,您可以保存此的引用:
var that = this;
chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
that.bookmarks = bookmarkTreeNodes;
console.log(that.localName + '#' + that.id + ' in getTree.');
});
这是我问题的一部分,我不喜欢使用“绑定”,我担心这可能会有副作用,看起来更复杂
但另一个问题是getTree的异步特性
而且,属性甚至不存在于“创建”阶段,我不得不使用“准备就绪”
这是几乎最终的结果:
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 + '.');
},
这是我问题的一部分,我不喜欢使用“绑定”,我担心这可能会有副作用,看起来更复杂。