我可以在Meteor中对方法进行分组吗?

thu*_*hur 9 meteor

我从Meteor开始,想要组织我的方法......例如,我有两个集合:'a'和'b',都有插入方法..我想做类似的事情:

Meteor.methods({
    a: {
        insert : function(){
           console.log("insert in Collection a");
        }
      },
    b: {
        insert : function(){
           console.log("insert in Collection b");
        }
      }
});
Run Code Online (Sandbox Code Playgroud)

然后打电话
Meteor.call('a.insert');

有可能这样做吗?或者我该如何组织我的方法?

我不想做像'insertA'和'insertB'这样的方法

sai*_*unt 6

您可以使用以下语法:

Meteor.methods({
  "a.insert": function(){
    console.log("insert in Collection a");
  }
  "b.insert": function(){
    console.log("insert in Collection b");
  }
});
Run Code Online (Sandbox Code Playgroud)

这可以让你做到Meteor.call("a.insert");.


Chr*_*itz 5

基于saimeunt的想法,如果您关心代码中这些组的优雅,您还可以为代码添加辅助函数.然后你可以使用你喜欢的符号甚至任意嵌套组:

var methods = {
    a: {
        insert : function(){
           console.log("insert in Collection a");
        }
    },
    b: {
        insert : function(){
           console.log("insert in Collection b");
        },
        b2: {
            other2: function() {
                console.log("other2");
            },
            other3: function() {
                console.log("other3");
            }
        }
    },
};

function flatten(x, prefix, agg) {
    if (typeof(x) == "function") {
        agg[prefix] = x;
    } else {
        // x is a (sub-)group
        _.each(x, function(sub, name) {
            flatten(sub, prefix + (prefix.length > 0 ? "." : "") + name, agg);
        });
    }
    return agg;
}

Meteor.methods(flatten(methods, "", {}));
Run Code Online (Sandbox Code Playgroud)

然后用点符号调用,如:

Meteor.call('b.b2.other2');
Run Code Online (Sandbox Code Playgroud)