【问题标题】:how i return object contain function in meteorjs?我如何在meteorjs中返回对象包含函数?
【发布时间】:2014-09-19 13:45:27
【问题描述】:

我目前使用meteorjs 0.9.2

我想将一个对象从服务器方法返回给客户端方法调用

在该服务器返回的对象中包含一个函数作为值,我认为这可能与meteorjs EJSON有关

下面给出的服务器方法返回对象

        return EJSON.stringify({

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

        });

下面给出的客户端方法接收

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

但在浏览器控制台日志中我无法将该对象元素值作为函数,它显示下面给出的对象

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

我如何传递一个包含函数的对象作为返回?

【问题讨论】:

  • 你不能对函数进行字符串化
  • johan - 那么我如何传递函数? EJSON 可以吗?
  • 你没有。传递其他表明您的兴趣的价值并重建客户端。

标签: javascript json object meteor


【解决方案1】:

解决此类问题的正确方法是在客户端定义所有您感兴趣的函数,然后根据您传递的 EJSONable 值选择适当的函数。如果这是您的应用程序中的常见模式,您可以例如创建一个可能的操作字典:

Actions = {};

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

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

...

然后在你的 return 语句中传递动作名称:

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

然后在需要时调用请求的动作:

Actions[action.name].apply(this, action.arguments);

【讨论】:

    【解决方案2】:

    您可以在服务器上使用toString,在客户端使用eval

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

    只要确保您了解使用 eval 的 implications

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2011-03-28
      • 2018-12-29
      • 2017-08-27
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      相关资源
      最近更新 更多