1

i currently using meteorjs 0.9.2

i want to return an object from a server method to client method call

here in that server returning object contain a function as value, i think its possible to do with meteorjs EJSON

server method return object given below

        return EJSON.stringify({

            plotOptions: {
                series: {
                    stacking: 'normal',
                    point: {
                        events: {
                            click: function() {
                                alert('ok');
                            }
                        }
                    }
                }
            },

        });

client method receiving given below

Meteor.call("highcharts", Session.get("method"), Session.get("taskId"), function(error, object) {
    $("#highcharts #loading").hide();

    if(error) throwError(error.reason);
    else $("#highcharts").highcharts(JSON.parse(object));

    console.log(EJSON.parse(object));
});

but in browser console log i cant get that object element value as function, it show an object given below

{"plotOptions":{"series":{"stacking":"normal","point":{"events":{}}}}}

how i pass a object contain function as return ?

3
  • 1
    You can't stringify a function Commented Sep 18, 2014 at 20:31
  • johan - then how i pass function ? is it possible with EJSON ? Commented Sep 18, 2014 at 20:33
  • 1
    You don't. Pass other value stating your interests and rebuild that client side. Commented Sep 18, 2014 at 20:50

2 Answers 2

2

The correct way to solve such problem is to have all your functions of interest defined on the client side, and then choosing the appropriate function based on the EJSONable value you pass. If this is a common pattern in your app, you can for example create a dictionary of possible actions:

Actions = {};

Actions.alertOk = function() {
  alert('ok');
};

Actions.confirm = function(message) {
  if(confirm(message)) alert('ok');
};

...

Then in your return statement pass the action name:

return {
  ...
  action: {
    name: 'confirm',
    arguments: [
      'Do you want an OK alert?',
    ],
  }
};

And then call the requested action when needed:

Actions[action.name].apply(this, action.arguments);
Sign up to request clarification or add additional context in comments.

Comments

-1

You could use toString on the server and eval on the client.

//server
var str = (function click() {
  alert('ok');
}).toString();

//client
eval(str)();

Just make sure you understand the implications of using eval.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.