Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repetitive code in Meteor

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?

like image 826
DigiLord Avatar asked Jan 12 '23 23:01

DigiLord


1 Answers

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>
like image 113
Hubert OG Avatar answered Jan 21 '23 14:01

Hubert OG