Man*_*ook 5 javascript cytoscape.js polymer
所以我有一个问题,这很可能是因为我仍然没有得到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>
Run Code Online (Sandbox Code Playgroud)
var cy;
cytoscape({
ready : function () {
Polymer: ({
...
properties : {
node : {
type : Object,
notify : true,
readOnly : true
}
},
...
Run Code Online (Sandbox Code Playgroud)
// 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();
});
},
Run Code Online (Sandbox Code Playgroud)
但为了更新我,<div>{{node.label}}</div>我必须能够做到,this.node.label = "N42" // Polymer但我不能这样做,cy.on('click','node', ... )因为我需要this.data() // Cytoscape在里面.
范围实际上是在扼杀我.
编辑
最后,我创建了一个Observer来观察和更新:
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));
Run Code Online (Sandbox Code Playgroud)
我发现这是 JS 开发初学者中常见的问题。您必须将该函数绑定到其正确的this引用。
cy.on('click', 'node', {
"nodedata" : rhynode
}, function (e) {
e.data.nodedata = this.data();
console.log(e.data.nodedata);
}.bind(this)); // here
Run Code Online (Sandbox Code Playgroud)
在 ES2015 中,箭头函数将自动绑定到正确的this:
cy.on('click', 'node', {
"nodedata" : rhynode
}, (e) => {
e.data.nodedata = this.data();
console.log(e.data.nodedata);
});
Run Code Online (Sandbox Code Playgroud)