Polymer this and cytoscape this

So, I have a problem, and this is most likely because I still do not get JavaScript ... Cytoscape has its own 'this', and Polymer has '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(); }); }, 

But to update my <div>{{node.label}}</div> I have to be able to do this.node.label = "N42" // Polymer , but I cannot do this in cy.on('click','node', ... ) because I need this.data() // Cytoscape inside.

Scope really kills me about this.

EDIT

In the end, I created an Observer to view and update:

  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)); 
+5
source share
1 answer

I find this common among JS dev newbies. You need to bind the function to its correct this link.

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

With ES2015, arrow functions are automatically bound to the correct this :

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

Source: https://habr.com/ru/post/1234314/


All Articles