Search code examples
javascriptmeteoriron-router

Is there a way to detect changes within the same route?


With Iron Router, I have the following route set up:

Router.route('/:cat', {
    name: "goods",
    waitOn: function() {
        Session.setDefault('limit', 20)
        var limit = Session.get('limit') || 20
        Meteor.subscribe('goods', this.params.cat, limit)
    }
})

The idea is that the user can press a bunch of buttons to change the cat(egory), filtering out some data but remaining on the same route. Classic stuff.

Right now it just sets a default limit of 20 and as the user scrolls down, it is increased. If he clicks a button to change category, it doesn't make sense to instantly load 100 new items, but set the limit back to 20 again.

Problem is, I can't really think of a good way to do that. Removing the setDefault to use a Session.set won't work. All I can think of right now is logging the cat in a Session and use that to check if the category has been changed, but I was hoping there is a better way.


Solution

  • How about using the template to manage the state (instead of sessions and the route.

    For example, using a reactivate variable (reactive-var package), and passing the category through the route to the template. This way - categories can be linked to (and the limits expanded/limited as needed).

    Start by instantiating the template

    Template.limitedDatasource.created = function() {
      this.data.limitVar = new ReactiveVar(20);
      this.data.dsSub = Meteor.subscribe('goods', this.data.category, this.data.limitVar.get())
    }
    

    Add some template level helpers to manage the subscription readyness and the data

    Template.limitedDatasource.helpers({
        dataSourceReady: function() {
            return this.dsSub.ready();
        },
        dataSource: function() {
            return CollectioName.find({cat: this.category}, {limit: this.limitVar.get()});
        }
    });
    

    Add some event handlers to load in more things (maybe change the limit?)

    Template.limitedDatasource.events({
        'click .showMore': function(event, template) {
            event.preventDefault();
            var newLimit = template.data.limitVar.get() + 20;
            template.data.limitVar.set(newLimit);
        },
    
    });