Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-side-only reactivity with Meteor?

Tags:

meteor

I have a collection published on the server and auto-subscribed on the client. I'd like to set the 'selected' item on the session and have the template update to display only the selected item, but it seems this can only be done with a roundtrip to the server (which is totally unnecessary).

Common:

var Missions = new Meteor.Collection('missions');

Client:

Template.missionList.missions = function() {
    var currMission = Session.get('selectedMission');
    var searchMission = {};
    if(currMission)
    {
        searchMission['_id'] = currMission;
    }
    return Missions.find(searchMission);
};
Template.missionList.events({
    'click div.mission': function (e, t) {
        Session.set('selectedMission', 
            this._id == Session.get('selectedMission') ? null : this._id
        );
    }
});
Template.mission.isSelected = function() {
    return this._id == Session.get('selectedMission');
};
Meteor.autosubscribe(function () {
    Meteor.subscribe("missions");
});

Server:

Meteor.publish('missions', function() {
    // there are really some filters here, but removed for simplicity
    return Missions.find(); 
});

Template:

<template name="missionList">
    <div class="missionList">
    {{#each missions}}
        {{> mission}}
    {{/each}}
    </div>
</template>

<template name="mission">
    <div class="mission{{#if isSelected}} selected{{/if}}">details</div>
</template>

My requirement is for the Missions.find() in Template.missionList.missions to filter the client-side cached results, rather than to re-request from the server, but I can't seem to find a flag or settings to allow me to tell minimongo to only use the currently available data.

I'm also not entirely sure if this is what I should be doing, I started out just using jQuery to hide the non-selected missions but getting my head round Meteor and it seems a natural fit to use the data and reactivity to drive selection/local-filtering.

Is there any way the roundtrip can be avoided or am I just using it wrong?

like image 602
Bob Davies Avatar asked Dec 18 '12 09:12

Bob Davies


1 Answers

By setting up a publish / subscribe relationship, you are creating a simplified form of database replication. Minimongo will have a copy of the data locally and execute the find() locally without a server roundtrip. If you are seeing network activity or calls to the server code, it is because meteor is regularly working behind the scenes to keep the subscription in sync with the server, not for your specific find.

This also means you have to wary of sending too much data to the client, so your server side publish function may want to filter by the specific fields needed by client, in addition to existing your selection criteria.

like image 85
David Wihl Avatar answered Nov 02 '22 11:11

David Wihl