HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Working with forms in Meteor, using selectors for every input

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
selectorswithworkingeverymeteorinputusingforforms

Problem

I'm trying to work with forms, and just getting a grasp on JavaScript. Basically I'm unsure if there is a more reusable way to handle forms with Meteor/jQuery.

// Creating a new prayer, including the preview
Template.newPrayer.events({
    'click input.save' : function() {            
        var title = $("#prayer_title");
        var prayer = $("#prayer");
        var preview_container = $("#prayer_preview");
        var currentUser = Meteor.userId();

        if( currentUser !== null ) {
            Prayers.insert({
                title: title.val(), 
                prayer: prayer.val(),
                user: currentUser });

            title.val('');
            prayer.val('');
            preview_container.fadeOut();
        }
    },
    // Auto-updating the preview
    'keyup #prayer' : function() {
        var preview_container = $("#prayer_preview");
        preview_container.fadeIn();
        var preview_formatted = prayer.value.replace(/\n/g,'');
        $(".preview_text").html(preview_formatted);
    }
});


Is there a better way to do this, should my template be laid out in a different way?


    {{title}}
    
        Title
        

        
        
    
    
        Preview
        
     


Is there a better way to handle form data and form display, without having selectors for every form element, and then having to clear each one?

It seems like I'm not utilizing the full potential of Meteor's reactivity and templating features. Also open to any other pointers/tips with my code. The code works as is.

P.S. This code is just me learning Meteor/JS and the beginning of a small project.

Solution

As far as I know, Meteor's reactivity is one-way: changes in data are reflected in the DOM. To go the other way (DOM to data) there's two common methods: 1) grabbing data directly from the DOM when it's needed (i.e. to save it) as you've done above and 2) binding DOM elements to data models, and using the data models for CRUD operations.

1 is simpler to implement, but 2 gives you more control over data-flow, subscriptions, and life-cycles. 2 has plenty of great libraries you can use, so you don't have to reinvent the wheel just to leverage these benefits. Backbone.js is probably the most well known plain-JavaScript library for this sort of thing (also check out Lo-Dash and Exoskeleton if you haven't), but the Meteor ecosystem may have a preferred library for this.

Context

StackExchange Code Review Q#20598, answer score: 2

Revisions (0)

No revisions yet.