Last active
August 3, 2018 11:32
-
-
Save MohammedEssehemy/02c7728cac0157f6024d9f28766d2bca to your computer and use it in GitHub Desktop.
[confirm before page leave - iron router] #Meteor #blaze #iron #router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Meteor } from 'meteor/meteor'; | |
import { Template } from 'meteor/templating'; | |
import 'meteor/aldeed:template-extension'; | |
import { $ } from 'meteor/jquery'; | |
import { Router } from 'meteor/iron:router'; | |
import swal from 'sweetalert'; | |
// credits: https://stackoverflow.com/a/959679/7435863 | |
$.fn.extend({ | |
trackChanges() { | |
const $form = this; | |
$form.on('submit', () => { | |
$form.clearChanges(); | |
}); | |
$(':input', $form).change(() => { | |
$form.data('changed', true); | |
}); | |
}, | |
isChanged() { | |
return this.data('changed'); | |
}, | |
clearChanges() { | |
return this.data('changed', false); | |
}, | |
}); | |
Template.onRendered(() => { | |
// schedule after one second to ignore autoform changes to the form | |
setTimeout(() => { | |
$('form').trackChanges(); | |
}, 1000); | |
}); | |
const getAbsoluteUrl = (url = '') => (url.startsWith('http') ? url : Meteor.absoluteUrl(url)); | |
let stoppingUrl; | |
let targetedUrl; | |
// credits: https://github.com/iron-meteor/iron-router/issues/698#issuecomment-312350115 | |
// credits: https://gist.github.com/dferber90/acf560226fe76fe91534 | |
Router.onRun(function storeNextPath({ url }) { | |
const nextUrl = getAbsoluteUrl(url); | |
if (stoppingUrl && (nextUrl !== stoppingUrl)) targetedUrl = nextUrl; | |
this.next(); | |
}); | |
Router.onStop(function RouterOnStopConfirm() { | |
const isFormDirty = $('form').toArray().find(ele => $(ele).isChanged()); | |
if (!isFormDirty || stoppingUrl) return; | |
stoppingUrl = getAbsoluteUrl(this.url); | |
this.redirect(stoppingUrl); | |
swal({ | |
title: 'بعض التعديلات لم يتم حفظها', | |
text: 'هل تريد الاستمرار إلى الصفحة التالية و حذف ما لم يتم حفظه؟', | |
icon: 'warning', | |
dangerMode: true, | |
buttons: [ | |
'رجوع إلى الصفحة', | |
'نعم', | |
], | |
}).then((confirmed) => { | |
stoppingUrl = null; | |
if (confirmed) { | |
$('form').each((idx, ele) => { $(ele).clearChanges(); }); | |
Router.go(targetedUrl); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment