javascript - meteor: design pattern : create template helper for each field (column) of collection -
using meteor js, notice if have documents
{"q1":"somevalue1","q2":"somevalue2","q3":"somevalue3","q4":"somevalue4"}
quite helpers end edit: end repeating creation of helper-per-field lot
template.whatever.helpers({ gimmeresults1: function(){return mycollection.find({},{fields:{"q1":1}})}, gimmeresults2: function(){return mycollection.find({},{fields:{"q2":1}})} });
with averaging 1 field in ugly way such as
q1avg: function () { var count = mycollection.find({},{fields:{"q1":1}}).count(); var total = 0; mycollection.find({},{fields:{"q1":1}}).map(function(doc) { total += doc.q1; }); return avg = (math.round((total / count)*100))/100; }
(using variable still entail multiple db queries, correct?)
is there design pattern should using iterate on fields of document and-autocreate template helpers?
what other ways can eliminate spaghetti code?
the first step might this:
getfield = function(collection, field) { var projection = {}; projection[field] = 1; return collection.find({}, {fields: projection}); } ui.registerhelper("getfield", getfield);
which call in templates {{getfield mycollection "q1"}}
, helper returning mycollection
. take further:
var makefieldgetter = function(collection, field) { return function() { return getfield(collection, field); }; }; template.whatever.helpers({ gimmeresults1: makefieldgetter(mycollection, "q1") gimmeresults2: makefieldgetter(mycollection, "q2") });
or further:
var makefieldgetters = function(collection, fields) { var obj = {}; fields.foreach(function(field) { obj["gimme_" + field] = makefieldgetter(collection, field); }); return obj; }; template.whatever.helpers(makefieldgetters(mycollection, ["q1", "q2"])); // creates helpers gimme_q1, gimme_q2
Comments
Post a Comment