Yeats
Yeats

Reputation: 2065

How to reach data within Iron Router?

On my page, which has the url object/:_id, the user should normally be accessing just one document, which I have set up like so:

waitOn: function() {

    return Meteor.subscribe('objects', this.params._id),
},

data: function() {
    return Objects.findOne({_id: this.params._id})
}

However, it should also be possible to take a peek at and work with some other objects, but only those of the same color as the object we're looking at, so I need to have those accessible as well.

Here's what I thought would work:

onBeforeAction: function() {
    var self = Objects.findOne({_id: this.params._id})
    var color = self.color
    Session.set('chosenColor', color)
    this.next()
},

waitOn: function() {
    return Meteor.subscribe('objects', Session.get('chosenColor'))
},

data: function() {
    return Objects.findOne({_id: this.params._id})
}

It should be noted that this worked at first, but then suddenly and inexplicably stopped working. self is now always "undefined" for some reason.

What is a correct way to access this data within Iron Router?

Upvotes: 0

Views: 34

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20256

You've got circular logic here: you're trying to load an object and get its color before you subscribe to the collection that's going to publish the object. Just move the color logic to the publishing function on the server.

client js:

waitOn: function() {

    return Meteor.subscribe('objects', this.params._id);
},

data: function() {
    return Objects.findOne({_id: this.params._id})
}

server js:

Meteor.publish('objects',function(id){
  check(id, Meteor.Collection.ObjectID);
  var self = Objects.findOne({_id: id})
  if ( self ){
    var color = self.color;
    return Objects.find({ color: color });
  }
  else this.ready();
});

Upvotes: 1

Victor Deplasse
Victor Deplasse

Reputation: 698

Try with a this.ready() condition in data:

waitOn: function() {
    return Meteor.subscribe('objects');
},

data: function() {
    if (this.ready()) {
        var self = Objects.findOne({_id: this.params._id});
        var color = self.color;

        return Objects.findOne({_id: this.params._id}, color);
    }
}

Upvotes: 0

Related Questions