你当然可以使用这种模式。你需要做的只是除了是设置您打算在会议中删除的用户ID,所以它是你的删除方法访问:
Template.user.events({
'click .delete': function(){
Session.set('confirmAction', 'delete');
Session.set('confirmText', 'Are you sure?');
Session.set('showConfirm', true);
/* addition - this._id refers to the id of the user in this template instance */
Session.set('userToDelete', this._id);
}
});
然后:
Template.confirm.events({
"click button.confirm": function(){
Meteor.call(
"deleteUser",
Session.get("userToDelete"),
function(error, result){
Session.set("userToDelete", null);
}
);
}
});
但是更灵活且可扩展的模式是使用附加到模板实例的ReactiveVar
或ReactiveDict
来获取并设置您确认删除用户模板内部的用户。这样你就不会用真正只涉及一个行为的键加载全局Session对象。你可以在其他不相关的环境中重复使用你的confirm
模板。
UPDATE
这里是重复使用跨情境确定按钮带有私人无功无功的方式。要查看是否有其他确认框已打开,您可以先检查会话属性。
Session.setDefault("confirming", false);
在confirm
模板text
和action
属性是从它的用户父设置:
<template app="app">
{{#each user}}
{{> user}}
{{/each}}
</template>
<template name="user">
<h1>{{name}}</h1>
<button class="delete">delete user</button>
{{#if show}}
{{> confirm text=text action=action}}
{{/if}}
</template>
<template name="confirm">
{{text}}
<button class="cancel">cancel</button>
<button class="confirm">{{action}}</button>
</template>
而且我们在用户父设置的助手和事件一样好:
Template.user.created = function(){
this.show = new ReactiveVar(false);
}
Template.user.helpers({
name: function(){
return this.name;
},
show: function(){
return Template.instance().show.get();
},
text: function(){
return "Are you sure?";
},
action: function(){
return "delete user";
}
});
Template.user.events({
"click button.delete": function(event, template){
if (Session.get("confirming")){
console.log("You are already confirming another deletion.");
return;
}
Session.set("confirming", true);
template.show.set(true);
},
"click button.confirm": function(event, template){
Meteor.call(
"deleteUser",
this._id,
function(error, result){
template.show.set(false);
Session.set("confirming", false);
}
)
}
});
现在,您可以根据其父项为confirm
模板提供其他位置的其他上下文。
不会同时解决用户删除问题吗?如果我想删除其他帐户,或者当我使用确认框确认订单,该怎么办?我已经尝试过使用ReactiveVar,但是如果我打开一个新的盒子,如何关闭其他盒子? – Slemgrim
我编辑了我的答案以显示可能的解决方案 - 让我知道这是否有帮助。 –
这帮了我很多!谢谢你,杰里米。我一直在用错误的方式使用ReactiveVar。这个变化很大 – Slemgrim