Dcat.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. let $ = jQuery,
  2. pjaxResponded = false,
  3. bootingCallbacks = [],
  4. defaultOptions = {
  5. pjax_container_selector: '#pjax-container',
  6. };
  7. export default class Dcat {
  8. constructor(config) {
  9. this.withConfig(config);
  10. }
  11. booting(callback) {
  12. bootingCallbacks.push(callback);
  13. return this
  14. }
  15. boot() {
  16. bootingCallbacks.forEach(callback => callback(this));
  17. bootingCallbacks = []
  18. }
  19. ready(callback, _window) {
  20. if (! _window || _window === window) {
  21. if (! pjaxResponded) {
  22. return $(callback);
  23. }
  24. return $(document).one('pjax:loaded', callback);
  25. }
  26. var proxy = function (e) {
  27. _window.$(_window.$(this.pjaxContainer)).one('pjax:loaded', proxy);
  28. callback(e);
  29. };
  30. _window.Dcat.ready(proxy);
  31. }
  32. withConfig(config) {
  33. this.config = $.extend(defaultOptions, config);
  34. this.withLang(config.lang);
  35. this.withToken(config.token);
  36. delete config.lang;
  37. delete config.token;
  38. return this
  39. }
  40. withToken(token) {
  41. token && (this.token = token);
  42. return this
  43. }
  44. withLang(lang) {
  45. lang && (this.lang = lang);
  46. return this
  47. }
  48. /**
  49. * 如果是 pjax 响应的页面,需要调用此方法
  50. *
  51. * @returns {Dcat}
  52. */
  53. pjaxResponded() {
  54. pjaxResponded = true;
  55. return this
  56. }
  57. reload(url) {
  58. let container = this.config.pjax_container_selector;
  59. let opt = {container: container};
  60. url && (opt.url = url);
  61. $.pjax.reload(opt);
  62. }
  63. }