Expose all utils function as @utils

This commit is contained in:
Paul Chavard 2018-10-09 11:32:27 +02:00
parent 552468e6d9
commit c343893d00
2 changed files with 53 additions and 0 deletions

View file

@ -1,3 +1,10 @@
import Rails from 'rails-ujs';
import $ from 'jquery';
import debounce from 'debounce';
export { debounce };
export const { fire } = Rails;
export function show({ classList }) {
classList.remove('hidden');
}
@ -9,3 +16,40 @@ export function hide({ classList }) {
export function toggle({ classList }) {
classList.toggle('hidden');
}
export function delegate(eventNames, selector, callback) {
eventNames
.split(' ')
.forEach(eventName =>
Rails.delegate(document, selector, eventName, callback)
);
}
export function getJSON(url, data, method = 'get') {
data = method !== 'get' ? JSON.stringify(data) : data;
return $.ajax({
method,
url,
data,
contentType: 'application/json',
dataType: 'json'
});
}
export function scrollTo(container, scrollTo) {
$(container).scrollTop(
$(scrollTo).offset().top -
$(container).offset().top +
$(container).scrollTop()
);
}
export function scrollToBottom(container) {
$(container).scrollTop(container.scrollHeight);
}
export function on(selector, eventName, fn) {
[...document.querySelectorAll(selector)].forEach(element =>
element.addEventListener(eventName, event => fn(event, event.detail))
);
}

View file

@ -1,3 +1,4 @@
const path = require('path');
const { environment } = require('@rails/webpacker');
// By default don't transpile JS files in ./node_modules except for some specific modules.
@ -14,4 +15,12 @@ babelLoader.exclude = function(modulePath) {
);
};
const resolve = {
alias: {
'@utils': path.resolve(__dirname, '..', '..', 'app/javascript/shared/utils')
}
};
environment.config.merge({ resolve });
module.exports = environment;