In Meteor, how to short-circuit-assign a helper variable with user object? -


i'm running latest meteor (v1.1.0.3) on os x 10.6.8 in firefox 39.0. i'm using accounts-ui , accounts-google login management. have hand-rolled profile form (among other things) 'name' field. initial value of field should either name set in profile or 1 google supplies.

i've defined following template helper:

template.profile_edit.helpers({     my_name: (function () {var u=meteor.user(); return u.profile.name || u.services.google.name;}()) }); 

i use value in template {{ my_name }}. when start meteor compiles fine, when load profile page following javascript error:

typeerror: u undefined ...me: (function () {var u=meteor.user(); return u.profile.name || u.services.googl... 

not relevant, completeness:

  • after page loads, 'name' field in form blank.
  • i am logged in.
  • when pull meteor's mongo instance in terminal can see user record; name in profile not set, name in services.google.name set.

why error happening , how can solve it?

the problem

this common issue people have when first starting out meteor. problem when helper executed during page load, depending on response time publication server, data logged in user may not available yet. makes seem intermittent because @ times data published in time, , others it's not.

possible solutions

one possible solution install meteorhacks:fast-render. publish logged in user (due null publication) initial html page , guarantee user available when helper run. data other logged in user need set subscriptions on router fast render take effect.

the other solution, , 1 work without installation of new package guard against undefined. let helper return undefined when there no data, once data available helper reactively rerun , proper data returned.

template.profile_edit.helpers({     my_name: function () {         var u=meteor.user();         if(u){           return u.profile.name || u.services.google.name;         }     } }); 

aside

in helper notice using syntax my_name:(function(){}()). while give seems desired outcome, problem invoking function , assigning value my_name helper instead of assigning function can called multiple times when value changes. breaks reactivity , second solution not work due it's reliance on it.

template.profile_edit.helpers({     my_name: (function () {         /*            invoked ,            using my_name: "bob"         */      }()) }); 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -