Pelle Mårtenson
Pelle Mårtenson

Reputation: 40

How do you do client side routing when saving via methods?

I want to save some data and show it in a view template. So I want to do like the example below but using methods.

Template.postSubmit.events({
  'submit form': function(e) {
    e.preventDefault();

    var post = {
      url: $(e.target).find('[name=url]').val(),
      title: $(e.target).find('[name=title]').val()
    };

    post._id = Posts.insert(post);
    Router.go('postPage', post);
  }
});

I tried this:

'insertClubData': function(clubname, capacity, description, homepage){
    var currentUserId = Meteor.userId();
    var club = {
        clubname: clubname,
        description: description,
        capacity: parseInt(capacity),
        homepage: homepage,
        createdAt: new Date(),
        visitors: 0,
        occupancy: 0,
        trend: "club-1",
        createdBy: currentUserId
    }

    club._id = clubs.insert(club);
    Router.go('club', club);
}, 

but I get the error:

Exception while invoking method 'insertClubData' TypeError: Object function router(req, res, next) { I20160425-14:04:55.724(2)? //XXX

this assumes no other routers on the parent stack which we should probably fix

I understand that this is because Router.go is a client side method. But I also understand that you should avoid server side routing. So what's the most elegant solution?

This is my route:

Router.route('/club/:_id', {
    name: 'club',
    template: 'club',
    data: function(){
        return clubs.findOne({_id: this.params._id})
    }
});

Upvotes: 1

Views: 89

Answers (1)

tomsp
tomsp

Reputation: 1807

How about, you call the method from the client and in the callback on success you do the routing. For example:

Template.postSubmit.events({
  'submit form': function(e) {
    e.preventDefault();

    var post = {
      url: $(e.target).find('[name=url]').val(),
      title: $(e.target).find('[name=title]').val()
    };

    Meteor.call('insertPost', post, function(error, id) {
      if (error) {
        alert(error)
      } else {
        Router.go('postPage',  {_id: id});
      }
    });
  }
});

and on the server

Meteor.methods({
  insertPost: function(post) {
    // do checks
    id = Posts.insert(post);
    return id;
  }
});

Does that work for you?

Upvotes: 1

Related Questions