Variables created in onCreated disappears on refresh

Hi, I have some (simplified sample) code like below

Template.modalSelect.onCreated(function(){
    var self=this;
    self.data.modalHelper = {};
    self.data.modalHelper.someStatus = new ReactiveVar("notsubmitted");
});

and then an event handler like so:

Template.modalSelect.events({
    'click #someButton': function(e, t) {
        self.modalHelper.someStatus.set('completed');  
    }
});

The variables all work properly, as intended the first time around, when the user signs in for the first time & access the page.

However, after (a) any event which uses the functionality (e.g. a button click triggering the event), or even (b) a browser page refresh, the onCreated variable ‘self.data.modalHelper’ disappears (self.data still exists).
If the user signs in and out (or I restart the server) it works properly again, for 1 time.

What could be the cause of this? Is there something wrong in how I am using onCreated?

Thanks for your help.

**Edit: One possible issue I think could be happening is overlapping context – ie the parent context being refreshed some how and removing the child’s context. How can I isolate data contexts of child templates in that case?

self is not defined in your event handler. Instead, try this

Template.modalSelect.events({
    'click #someButton': function(e, t) {
        t.data.modalHelper.someStatus.set('completed');  
    }
});

I am not 100% sure about this, but I feel like mutating the instance’s data object is not right. I usually create attributes in the instance directly like this.myData instead of this.data.myData.

The documentation is a bit brief and only says readonly

Can someone please clarify whether that is a good practice?

2 Likes

@tosi is right.
While you can modify data it will be lost if any changes come from the parent template. Custom properties and variables should go on the instance. Losing the content of data is exactly whats happening here:

Worse, may browsers treat self as the same as window, so you’re accidentally using global instead of scoped variables.

Variables aren’t meant to survive a page refresh. You can use Session or a named ReactiveDict for that

1 Like