riot-js

Open full view…

How to access tag 'this' inside this.on('updated')

skwny
Thu, 15 Dec 2016 08:46:10 GMT

I'm trying to update an array every time my tag receives an update from parent tags. Here is my code: --- function(opts){ this.set = []; var self = this; this.on('updated', function(){ var obj = opts.my_topics; var better_obj = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var topic_title = key; better_obj = obj[key]; better_obj['title'] = key; } } self.set.push(better_obj); }) } --- Whenever I try to push(), I get an error: `Uncaught SyntaxError: Unexpected token ; database.js:60`. The moment I remove the line of code for the push, the error disappears. Am I using this/self wrong in this case or could it be something else?

skwny
Thu, 15 Dec 2016 20:47:31 GMT

What I am trying to accomplish here is taking an object from opts, receives regular updates, converting into an array, and using it for an `each` loop within my tag. I do not know how to do this other than a) rewiring my opts to deliver an array rather than an object, or b) accessing the tag's `this` within the `updated` callback.

skwny
Mon, 19 Dec 2016 06:07:23 GMT

Is it not possible to do?

jaykuri
Tue, 31 Jan 2017 18:10:19 GMT

If I understand properly, what you want is to update the the tag that has been updated? If so - you want to use the .bind() method on the function: --- function(opts){ this.set = []; var self = this; this.on('updated', function(){ var obj = opts.my_topics; var better_obj = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var topic_title = key; better_obj = obj[key]; better_obj['title'] = key; } } self.set.push(better_obj); }.bind(this)); } --- This will ensure that the updated function has 'this' bound to your tag. the [.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) method is VERY useful, especially in riot, when you don't know exactly what might be calling your function or from where.

jaykuri
Tue, 31 Jan 2017 18:28:33 GMT

That should have been: --- function(opts){ this.set = []; this.on('updated', function(){ var obj = opts.my_topics; var better_obj = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var topic_title = key; better_obj = obj[key]; better_obj['title'] = key; } } this.set.push(better_obj); }.bind(this)); } --- note that there is no need for `self`

skwny
Thu, 02 Feb 2017 02:02:33 GMT

Ahhh, thank you very much!