gpt4 book ai didi

javascript - Polymer this 和 Cytoscape this

转载 作者:搜寻专家 更新时间:2023-11-01 04:40:42 25 4
gpt4 key购买 nike

所以我有一个问题,这很可能是因为我仍然没有得到 JavaScript...Cytoscape 有他们自己的“this”而 Polymer 有他们的“this”

    <div id="labelFld">{{node.label}}</div>
<div id="measureFld">{{node.measure}}</div>
<div id="timesignatureFld">{{node.time_signature}}</div>
<div id="voiceFld">{{node.voice}}</div>
<div id="beatFld">{{node.beat}}</div>
<div id="meventFld">{{node.event}}</div>
var cy;
cytoscape({
ready : function () {
Polymer: ({
...
properties : {
node : {
type : Object,
notify : true,
readOnly : true
}
},
...
// Fires when the local DOM has been fully prepared
ready : function () {
var self_node = this.node; // <- 'this' via Polymer
try {
cy = cytoscape({
container : this.$.rhythmgraph,
ready : function (e) {}
});
} catch (err) {
console.log(err);
}

// Assign handler to Cytoscape click event for node elements
cy.on('click', 'node', {
"nodedata" : self_node // <- Seems to pass by value, not reference
}, function (e) {
self_node = this.data(); // <- 'this' via Cytoscape
console.log(self_node);
// e.data.nodedata = this.data();
});
},

但是为了更新我的<div>{{node.label}}</div>我必须能够做到 this.node.label = "N42" // Polymer但我不能在 cy.on('click','node', ... ) 中做到这一点因为我需要this.data() // Cytoscape里面有。

Scope 在这方面真的让我很受不了。

编辑

最后,我创建了一个观察者来观察和更新:

    self_node = this.selectedNode;
var poly = this;

Object.observe(self_node, function(changes) {
changes.forEach(function(change) {
if(change.type == "update") {
poly.selectedNode = {
"id": change.object.id,
... }
};
poly.notifyPath('selectedNode.id', change.object.id);

}
});}.bind(poly));

最佳答案

我发现这是 JS 开发初学者的常见问题。您必须将该函数绑定(bind)到其正确的 this 引用。

cy.on('click', 'node', {
"nodedata" : rhynode
}, function (e) {
e.data.nodedata = this.data();
console.log(e.data.nodedata);
}.bind(this)); // here

在 ES2015 中,箭头函数会自动绑定(bind)到正确的 this:

cy.on('click', 'node', {
"nodedata" : rhynode
}, (e) => {
e.data.nodedata = this.data();
console.log(e.data.nodedata);
});

关于javascript - Polymer this 和 Cytoscape this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288790/

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