vue-scroll.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. (function(){
  2. var Vue;
  3. var isVueLoaded = true;
  4. if(typeof require === 'undefined'){
  5. Vue = Window.Vue;
  6. }else{
  7. Vue = require('vue');
  8. }
  9. if(!Vue) {
  10. isVueLoaded = false;
  11. console.warn('Vue is not loaded yet. Please make sure it is loaded before installing vue-scroll.');
  12. }
  13. var scrollPlugin = {
  14. install: function(Vue, options){
  15. var handleListeners = function(el, current, old){
  16. if(el==document.body){
  17. document.onscroll = function(e){
  18. current && current(e, { scrollTop: document.body.scrollTop, scrollLeft: document.body.scrollLeft});
  19. }
  20. }else if(el.addEventListener){
  21. old && el.removeEventListener('scroll', old);
  22. el.addEventListener('scroll',function(e){
  23. current && current(e, { scrollTop: el.scrollTop, scrollLeft: el.scrollLeft});
  24. });
  25. }else {
  26. old && el.detachEvent('onscroll', old);
  27. el.attach('onscroll',function(e){
  28. e = e || window.event;
  29. current && current(e, { scrollTop: el.scrollTop, scrollLeft: el.scrollLeft});
  30. });
  31. }
  32. }
  33. Vue.directive('scroll', {
  34. bind: function(el, binding, vnode){
  35. if(!binding.value || typeof binding.value !== 'function'){
  36. throw new Error('The scroll listener is not a function');
  37. }
  38. handleListeners(el, binding.value, binding.oldValue);
  39. },
  40. inserted: function(el, binding){
  41. //To do, check whether el is scrollable and give warn message if it's not'
  42. },
  43. update: function(el, binding){
  44. if(binding.value === binding.oldValue){
  45. return;
  46. }
  47. if(!binding.value || typeof binding.value !== 'function'){
  48. throw new Error('The scroll listener is not a function');
  49. }
  50. handleListeners(el, binding.value, binding.oldValue);
  51. },
  52. unbind: function(el, binding){
  53. if(binding.value && typeof binding.value === 'function'){
  54. if(el.removeEventListener){
  55. el.removeEventListener('scroll', binding.value);
  56. }else{
  57. el.detachEvent('onscroll', binding.value);
  58. }
  59. }
  60. }
  61. })
  62. }
  63. }
  64. if(typeof module !== 'undefined' && typeof module.exports !== 'undefined'){
  65. module.exports = scrollPlugin;
  66. }else{
  67. window.vScroll = scrollPlugin;
  68. }
  69. })()