简体   繁体   中英

Meteor pass data from client to server

I have a registration form, and when the user clicks the submit button the value in every textbox will be sent to server to insert that data, and return true/false.

Client:

Template.cust_register.events({
    'click button': function(){
          var email = $('#tbxCustEmail').val();
          var msg = $('#tbxCustMsg').val();
          var isSuccess = insertMsg(email,msg);
          if(isSuccess){
             alert("Success");
          }else alert("Try again");
    }
});

Server:

function insertMsg(email,msg){
     Messages.insert({Email:email,Message:msg});
     return true;
}

This turned out to not work. How to solve this? Many people said "use publish/subscribe", but I don't understand how to use that.

First, watch the introductory screencast and read the Data and security section of the docs.

Your code in a publish/subscribe model would look like this:

Common:

Messages = new Meteor.Collection('messages');

Client:

Meteor.subscribe("messages");

Template.cust_register.events({
    'click button': function(){
          var email = $('#tbxCustEmail').val();
          var msg = $('#tbxCustMsg').val();
          Messages.insert({Email:email,Message:msg});
    }
});

Server:

Meteor.publish("messages", function() {
    return Messages.find();
});

An alternative solution is to use Meteor.call('yourMethodName') (on the client).

Then, on the server, you can have

Meteor.methods({
    yourMethodName: function() { /* validate input + return some data */ }
});

You can consider setting a session variable to the return value.

Meteor.call('yourMethodName', function (err, data) {
    if (!err) {
        Session.set('myData', data);
    } 
});

And then in some some template...

Template.whatever.helpers({
    messages: function() {
        return Session.get('myData');
    }
});

Why do all this?

1) You can explicitly deny all direct `insert/update/find` queries from the client, and force usage of pre-defined Meteor methods.

2) You can manually determine when certain data is "refreshed".

Obviously, this methodology undermines the value of the subscription/publication model, and it should only be used in cases where real-time data isn't required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM