Jim Mack created a good example that proves how well it works for storing db data, as well as additional conversion properties in the Session variable. Unfortunately, this example is not reactive and does not perform the desired “transformations” after re-rendering the Meteor magic. So I grabbed his cool code and added reactivity back, this is thin code that works very well, but will surpass Jim Max's example in terms of efficiency.
lolz.html
<head> <title>lolz</title> </head> <body> {{>myItems}} </body> <template name="myItems"> <h3>Reactive Item List with additional properties</h3> <button id="add">add</button> <button id="remove">remove</button> <dl> {{#each items}} <dt>data: {{caption}}</dt> <dd>added property: {{anotherProp _id}}</dd> {{/each}} </dl> </template>
lolz.js
items = new Meteor.Collection('Items'); if (Meteor.isServer) { items.allow({ insert: function (userid, doc) { return true; }, remove: function(userid,doc){ return true; } }); while(items.find().count()>0){ items.remove(items.findOne()._id); } while (items.find().count() < 3) { items.insert({caption: 'LOLCATZ RULZ'}); } Meteor.publish('Items', function () { return items.find(); }); Meteor.methods({ 'getAdditionalProps': function() { additionalProps={}; items.find().forEach(function(doc){ additionalProps[doc._id]=reverse(doc.caption); }); return additionalProps; } }); function reverse(s){ // server side operation, ie for security reasons return s.split("").reverse().join(""); }; } if (Meteor.isClient){ Meteor.subscribe('Items'); Meteor.startup(function(){ getAdditionalProps(); itemsHandle=items.find().observe({ added : function(doc){ getAdditionalProps(); }, removed : function(doc){ getAdditionalProps(); }, changed : function(docA,docB){ getAdditionalProps(); } }); }); Template.myItems.rendered=function(){ console.log(new Date().getTime()); }; Template.myItems.items=function(){ return items.find(); } Template.myItems.anotherProp=function(id){ return Session.get('additionalProps')[id]; } Template.myItems.events({ 'click #add':function(e,t){ items.insert({caption: 'LOLCATZ REACTZ'}); }, 'click #remove':function(e,t){ items.remove(items.findOne()._id); } }); } function getAdditionalProps(){ setTimeout(function(){ Meteor.call('getAdditionalProps',function(error,props){ Session.set('additionalProps',props); }); },0); }
Moritz walter
source share