我花了好一個半小時試圖弄清楚這裏有什麼問題,而且我沒有任何運氣。真的很感謝一些幫助,提前致謝!流星forEach()無法解釋的改變傳遞的變量
我的問題似乎是在下面的sendMailing()meteor方法的「Roles.getUsersInRole(mailingAttributes.role).forEach」循環中,由客戶端調用傳遞的變量「mailingAttributes」以某種方式被覆蓋,等通過foreach()循環第二輪,沒有什麼的.replace()的替換
1 -這裏是一個被髮送到sendMailing對象的實例()流星法,以及forEach()循環首次運行時如何出現
{
role: "admin", //Which user group to send the email to
subject: "Hello [[firstName]]!", //Email subject
html: "<h1>Hello [[firstName]] [[lastName]], how do you do?</h1>", //HTML Email
text: "Hello [[firstName]] [[lastName]], how do you do?" //Plain Text Email
}
2 -現在在foreach()將用戶對象和替換與用戶屬性的佔位符(第一&姓)
3 -鑑於用戶鮑勃·瓊斯,這裏是如何同一個對象的示例出現第二次foreach()循環中運行,其中該物體應該是儲存
{
role: "admin", //Which user group to send the email to
subject: "Hello Bob!", //Email subject
html: "<h1>Hello Bob Jones, how do you do?</h1>", //HTML Email
text: "Hello Bob Jones, how do you do?" //Plain Text Email
}
所以沒有什麼的.replaces()來改變......但我永遠不會改變的變量(mailingAttributes)...所以例1和2之間應該沒有區別
這裏是我的實際代碼:
function sendMailingEmail(mailingAttributes) {
//Send email
Email.send({
from: '[email protected]',
to: mailingAttributes.to,
subject: mailingAttributes.subject,
html: mailingAttributes.html,
text: mailingAttributes.text,
});
}
//Set up rate limiting on the email send function
var sendMail = rateLimit(sendMailingEmail, 75); // wait at least 75 milliseconds between calls (1 second/14 emails)
Meteor.methods({
sendMailing: function(mailingAttributes) {
//Check incoming attributes
check(mailingAttributes, {
role: String,
subject: String,
html: String,
text: String
});
// Confirm the user is logged in
if (this.userId === null || !Roles.userIsInRole(this.userId, 'admin'))
throw new Meteor.Error(401, 'You must be logged in and authorized');
Roles.getUsersInRole(mailingAttributes.role).forEach(function(userObject) {
//Create a temporary copy of the passed attributes
var userMailingAttributes = mailingAttributes;
//Make sure the user is subscribed to mailings
if (userObject.profile.subscribed === true) {
//Replace placeholders in text with user profile information
userMailingAttributes.subject = userMailingAttributes.subject.replace("[[firstName]]", userObject.profile.firstName).replace("[[lastName]]", userObject.profile.lastName);
userMailingAttributes.text = userMailingAttributes.text.replace("[[firstName]]", userObject.profile.firstName).replace("[[lastName]]", userObject.profile.lastName);
userMailingAttributes.html = userMailingAttributes.html.replace("[[firstName]]", userObject.profile.firstName).replace("[[lastName]]", userObject.profile.lastName);
userMailingAttributes.to = userObject.emails[0].address;
//Call the rate limited function, passing along the temporary copy of passed attributes (edited above)
sendMail(userMailingAttributes);
}
});
}
});
我使用的alanning:角色& dandv:限速包
使用了Underscore的_.clone(),它像一個魅力一樣工作!非常感謝你指點我正確的方向! – DanielRHarris
注意:使用下劃線的_.clone保存對嵌套元素的引用。雖然你沒有在這裏做,如果你想在嵌套對象上使用它,你應該檢查出lodash的cloneDeep https://lodash.com/docs#cloneDeep – challett