Ben
Ben

Reputation: 5087

reactive variable to capture user input (Meteor)

I'm still trying to wrap my head around the reactive programming model in Meteor, so this is probably a silly question, but:

Can I use the template system to extract data, rather than "inject" it, as is documented. That is, say I have a textarea like so

     <textarea id="desc" rows="15" cols="80" >  {{projectDescription}} </textarea>

Is it then possible to have access to the projectDescription field as a reactive data source, as it were? I didn't get anywhere with Template.project.projectDescription at the REPL, but as I say, I'm new to this game.

If what I propose is impossible, what's the idiomatic approach? Like, where would I put my

document.getElementById('desc').value

Is an event map on the template the way this was designed to be done? The point of this is to, say, validate that an input is unique (a server question) or do on-the-fly mkdn (like is happening RIGHT NOW as I type...). But mostly, I'm trying to get a feel for Meteor.

Upvotes: 6

Views: 2917

Answers (3)

Dan Dascalescu
Dan Dascalescu

Reputation: 151885

The session-bind package claims to do just that: two-way input binding to session variables. I'm surprised there are no other "reactive input" packages on Atmosphere that do this.

Upvotes: 0

Kelly Copley
Kelly Copley

Reputation: 3158

Reactivity is only one way, You can however register an event on the template to catch the keydown event which could then set a session variable. Session variables are reactive data sources so you could then use the variable and a template helper to create your reactivity in another part of you template.

As an example:

<template name="project>
  <textarea id="desc"></textarea>
  <div>{{projectDescription}}</div>
</template>

-

Template.project.events({
  "keydown #desc": function (event) {
     var value = $(event.target).val();
     Session.set("projectDescription", value);
  }
});

Template.project.helpers({
  projectDescription: function () {
    var projectDescription = Session.get("projectDescription");
    //do processing
    return projectDescription;
  }
});

Upvotes: 6

matb33
matb33

Reputation: 2830

Meteor doesn't offer the type of two-way binding you may have encountered in some frameworks. There may be smart packages out there to help with this, but the vanilla way is to bind events to DOM elements:

Template.xyz.events({
    "keyup #desc": function (evt, template) {
        Session.set("projectDescription", evt.currentTarget.value);
    }
});

Upvotes: 2

Related Questions