I have been working on a small application in Meteor. I have noticed a pattern of code that is starting to bug me.
Template.userForm.helpers({
    name: function(){
        user = Meteor.users.findOne(Session.get('edit-user'));
        return user && user.profile.name;
    },
    _user_id: function(){
        user = Meteor.users.findOne(Session.get('edit-user'));
        return user && user._id;
    },
    email: function(){
        user = Meteor.users.findOne(Session.get('edit-user'));
        return user && user.emails && user.emails[0].address;
    },
});
The issue is seeing the variable && variable.attribute code repeated.  If I don't write the code that way I get errors about undefined variables.
Is there a better way to do this? What am I missing?
The return variable && variable.attribute is equivalent to more elaborate
if(variable) return variable.attrubite;
return false;
This is necessary, because if variable was null - which happens all the time between page load and collection inflation - calling variable.attribute raises an exception: null does not have attributes.
So no, there's no escape from that check. You can choose another flavor if this one bothers you - personally, I'm leaving actual return for the last line and check correctness earlier:
if(! variable) return null;
return variable.attribute;
What can be avoided, is this line - which is also repeated in all your helpers:
user = Meteor.users.findOne(Session.get('edit-user'));
In the above case, however, all the attributes belong to a single object. So why not pass this single object instead?
userForm.js:
Template.userForm.user = function() {
    return Meteor.users.findOne(Session.get('edit-user'));
}
userForm.html:
<template name="userForm">
    <span data-id="{{user._id}}">
        Name: {{user.name}}, email: {{user.email}}
    </span>
</template>
or even:
<template name="userForm">
    {{#with user}}
        <span data-id="{{_id}}">
            Name: {{name}}, email: {{email}}
        </span>
    {{/with}}
</template>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With