linto cheeran
linto cheeran

Reputation: 1472

how i return object contain function in meteorjs?

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 ?

Upvotes: 1

Views: 144

Answers (2)

Hubert OG
Hubert OG

Reputation: 19544

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);

Upvotes: 2

Neil
Neil

Reputation: 2147

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.

Upvotes: -1

Related Questions