2014-08-30 71 views
0

我正在构建一个朋友包,并且需要在创建的每个新用户文档上存储一些数据。我查看了文档,并找到了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, ...含义此代码永远不会实际运行。

我做错了尝试覆盖提供的软件包行为?

回答

0

Accounts.onCreateUser是你所说的绑定你的自定义函数。 “仅调用一次”意味着您只能绑定一个自定义函数。 如果没有别的结合自定义函数,onCreateUser将永远不会被称为

Eg.if你只是想添加会员&朋友按照你的代码,只是做:基于

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

+0

的问题是,这onCreateUser通话是在一个包。当我像你的例子那样做的时候,当他们将应用程序代码中的函数绑定到onCreateUser时,那些使用我的包的人会覆盖我的包的自定义onCreateUser行为,对吗? – Azeirah 2014-08-31 15:57:27

+0

是的,但是,如果他们没有调用'Accounts.onCreateUser',你的代码将永远不会运行。 – 2014-08-31 22:36:21