我有一个事件要删除我的应用中的实习消息:前面的按钮,点击事件调用方法。一切正常。
但在调用该方法之前,我想要一个确认框“你确定要删除此消息吗?”
使用标准确认js功能,工作正常。但标准的js确认......不允许造型。
所以我的想法是使用sweetalert:一切顺利,berts通知也是如此,但没有消息被删除..
在我的活动下方,确认框版本& sweetalert版本和方法。
谢谢!
确认框版
Template.Users.events({
'click .toggle-admin': function() {
Meteor.call('toggleAdmin', this._id);
},
'click button.delete-message':function() {
if(confirm('Are you sure?')) {
Meteor.call('deleteMessage', this._id, function(error) {
if(error) {
Bert.alert({
title: 'Error',
message: error.reason,
type: 'danger'
});
} else {
Bert.alert({
title: 'Success',
message: 'Message deleted.',
type: 'success'
});
}
});
}
}
});
sweetalert版
Template.Users.events({
'click .toggle-admin': function() {
Meteor.call('toggleAdmin', this._id);
},
'click button.delete-message':function() {
swal({
title: "Are you sure?",
text: "You will not be able to recover this message!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!"
}).then(function (){
Meteor.call('deleteMessage', this._id, function(error) {
if(error) {
Bert.alert({
title: 'Error',
message: error.reason,
type: 'danger'
});
} else {
Bert.alert({
title: 'Success',
message: 'Message deleted.',
type: 'success'
});
}
});
})
}
});
方式
Meteor.methods({
insertMessage: function(message) {
ContactMessages.insert(message);
},
deleteMessage: function(messageId) {
ContactMessages.remove({_id: messageId});
}
});
答案 0 :(得分:1)
本机window.confirm()
是同步的,并阻止执行的JS线程。这意味着一旦用户响应提示,它就会返回一个值,并从该点继续执行。这就是您可以成功使用this._id
的原因。
使用诸如swal2之类的异步API(使用promises),一旦解析或拒绝(传递给then
),就会传递一个函数来处理它。在这些回调中,this
不再指向原始对象,因此您需要通过使用闭包或通过词法将其与arrow function绑定来保留对它的访问(或其他所需数据)。 / p>
使用闭包:
Template.Users.events({
'click button.delete-message'() {
const id = this._id;
swal({
// ...
}).then(function (){ // `id` is available from external function
Meteor.call('deleteMessage', id, function(error) {
// ...
});
})
}
});
使用箭头函数进行词法范围绑定:
Template.Users.events({
'click button.delete-message'() {
swal({
// ...
}).then(() => { //bound to the current `this`
Meteor.call('deleteMessage', this._id, function(error) {
// ...
});
})
}
});