gpt4 book ai didi

javascript - 更新 Meteor 中已发布的集合

转载 作者:行者123 更新时间:2023-12-02 16:59:50 29 4
gpt4 key购买 nike

我正在尝试了解如何在 Meteor 中重新发布。我发布了“allCustomers”数据,该数据最初在页面加载时加载,其中包括当月的客户:

Meteor.publish("allCustomers", function () {

var pDate = moment().utc().toDate();
var dateFilter = GetWholeMonthFilterFromDate(pDate);
return Customers.find(dateFilter);
});

到目前为止一切都很好。我还有这种服务器方法,当用户选择与当前月份不同的月份时,该方法可以获取客户:

Meteor.methods({
allCustomers:function(pDate){

function GetWholeMonthFilterFromDate(pDate){
var firstDayOfMonth = new Date(pDate.getFullYear(), pDate.getMonth(), 1);
var lastDayOfMonth = new Date(pDate.getFullYear(), pDate.getMonth() + 1, 0);

var dateFilter =
{
"joined": {"$gte": firstDayOfMonth, "$lte": lastDayOfMonth}
};
return dateFilter;
}

var dateFilter = GetWholeMonthFilterFromDate(pDate);
return Customers.find(dateFilter).fetch();
},

我使用这个“allCustomers”服务器方法,如下所示:

Meteor.call("allCustomers", selectedDate, function(error, result){
if(error)
{
console.log('ERROR :', error);
return;
}
else
console.log(result);
});

我的问题是,当用户选择不同的日期时,如何使用 Meteor.call("allCustomers") 的结果集来更新初始发布的“allCustomer”数据?这意味着,即使我确实在控制台中看到了新客户(当回调执行时),我的页面仍然使用初始发布中的旧数据。如何使用 Meteor.call() 的结果重新更新已发布的数据?

提前致谢

最佳答案

尝试重新订阅allCustomers,这几乎不需要改进:

Meteor.publish("allCustomers", function (pDate) {
var dateFilter = GetWholeMonthFilterFromDate(pDate);
return Customers.find(dateFilter);
});

您的 allCustomers 发布函数已通过添加参数 pDate 进行修改,这比在内部创建 pDate 灵活得多。

通过这种方法,您可以使用参数pDate停止订阅并再次订阅

// UPDATED after @saimeunt comment 

if (Meteor.isClient) {
Meteor.startup(function(){
Tracker.autorun(function(){
Meteor.subscribe('allCustomers',Session.get("selectedDate"));
})
// initial selection
Session.set("selectedDate",moment().utc().toDate());
})
}

请记住更改 Session.set("selectedDate", DATE_PARAM) 菜单模板中的日期:

Template.tpl_name.events({
'click .month':function(e, tpl){
var DATE_PARAM = ... ;
Session.set("selectedDate", DATE_PARAM)
}
})

每次用户单击 .month 按钮时,Session.get("selectedDate") 都会发生更改,从而导致重新订阅。

Example showing this approach

关于javascript - 更新 Meteor 中已发布的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837084/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com