【问题标题】:Overriding a package method in Meteor覆盖 Meteor 中的包方法
【发布时间】:2014-09-01 06:40:42
【问题描述】:

我正在构建一个朋友包,我需要在每个新创建的用户文档上存储一些数据。我查看了文档,发现Accounts.onCreateUser。文档特别声明它只能被调用一次,其他调用将覆盖之前指定的行为。

所以我做的是:

  • 存储旧函数
  • 用添加所需数据的函数覆盖实际的onCreateUser 函数
  • 添加我的数据后,新函数会调用旧函数

.

if (Meteor.isServer) {
    var _onCreateUser = Accounts.onCreateUser.bind(Accounts);
    // Since onCreateUser overrides default behavior, and we don't want to restrict package users
    // by removing the onCreateUser function, we override onCreateUser to modify the user document before the regular onCreateUser call.
    Accounts.onCreateUser = function (func) {
        console.log('onCreateUser definition');
        _onCreateUser(function (options, user) {
            console.log('onCreateUser call, the user should now have a profile');
            if (!user.profile) {
                user.profile = options.profile || {};
            }
            if (!user.profile.friends) {
                user.profile.friends = [];
            }
            return func(options, user);
        });
    };
}

问题是,如果我查看服务器日志,我从来没有看到日志onCreateUser definitiononCreateUser call, ...,这意味着这段代码实际上从未运行过。

我在尝试覆盖提供的包行为时做错了吗?

【问题讨论】:

    标签: javascript meteor packages


    【解决方案1】:

    Accounts.onCreateUser 是您调用绑定自定义函数的方法。 “仅调用一次”意味着您只能绑定一个自定义函数。 如果没有其他方法绑定自定义函数,则永远不会调用 onCreateUser

    例如,如果您只想根据您的代码添加个人资料和朋友,只需执行以下操作:

    Accounts.onCreateUser(function (options, user) {
            console.log('onCreateUser call, the user should now have a profile');
            if (!user.profile) {
                user.profile = options.profile || {};
            }
            if (!user.profile.friends) {
                user.profile.friends = [];
            }
            return user;
    });
    

    根据您的评论,我建议创建一个问题/向 Meteor 提交一个拉取请求,以允许 Accounts.onCreateUser 将每个函数附加到一组钩子。

    您需要修改的代码在Accounts.insertUserDoc

    【讨论】:

    • 问题是这个 onCreateUser 调用在一个包中。当我像您的示例那样做时,使用我的包的人会在他们的应用程序代码中将函数绑定到 onCreateUser 时覆盖我的包的自定义 onCreateUser 行为,对吗?
    • 是的,但是如果他们不调用Accounts.onCreateUser,您的代码将永远不会运行。
    猜你喜欢
    • 2013-09-10
    • 2016-02-28
    • 2015-09-14
    • 2016-10-27
    • 1970-01-01
    • 2012-04-24
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多