chackerian
chackerian

Reputation: 1401

onBeforeAction running too late

I have a page with a helper that relies on a id_sell variable being set at routing with onBeforeAction. The issue currently is the helper runs before the variable is set.

this.route('/chat_id', {
    path: '/chat/:_id',
    template: 'Messages',
    layoutTemplate: 'LayoutMessages',
    onBeforeAction: function() {

      id = Session.get("recipientId");
      id_sell = this.params._id;
      this.next();
       }
    })

As you can see, this id_sell var is set here.

Unfortunately I get the error

Exception in template helper: ReferenceError: id_sell is not defined

When my helper tries to load in the value of the global var.

How can I solve this loading error

Upvotes: 0

Views: 53

Answers (2)

gaiazov
gaiazov

Reputation: 1960

It looks like you are using iron router, in which case you can change your route definition to

this.route('/chat_id', {
    path: '/chat/:_id',
    template: 'Messages',
    layoutTemplate: 'LayoutMessages',
    data: function() {
        return {
            id: this.params._id
        }
   }
})

and inside the Messages template you can access Template.currentData().id to access the variable.

Then, if you want to load something from the collection, you can change your route to

this.route('/chat_id', {
    path: '/chat/:_id',
    template: 'Messages',
    layoutTemplate: 'LayoutMessages',
    waitOn: function() {
        return Meteor.subscribe('messages');
    },
    data: function() {
        return {
            id: this.params._id,
            messages: Messages.find({ chatId: this.params._id })
        };
    }
});

and template will then have Template.currentData().messages available and {{#each messages}} will work in html.

(obviously replacing messages and Messages with names of your publication and collection, accordingly).

Finally, you can pass the this.params._id into the Meteor.subscribe(...) call to only subscribe to the item you care about - but that is another story.

Upvotes: 1

Lazov
Lazov

Reputation: 1476

You can use Session in order to ger the value of this variable before the helper runs. For example,

lib/router.js

Router.route('/chat/:_id', function(){
    Session.set("chatId", this.params._id);
    this.render("chatTemplate", {to:"main"});
});

main.js

Here use:

var id_sell = Session.get("chatId");

And the variable will be set here before the helper runs.

Upvotes: 0

Related Questions