Skip to content

Instantly share code, notes, and snippets.

@inakianduaga
Last active August 16, 2018 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inakianduaga/0f72ba3260347c5cb3b3f7231320a449 to your computer and use it in GitHub Desktop.
Save inakianduaga/0f72ba3260347c5cb3b3f7231320a449 to your computer and use it in GitHub Desktop.
Redux for vanillaJS Medium.com article - DOM bridge
// Some CSS styles for our component
import "./gallery.scss";
/**
* DOM mutations. Include all DOM manipulation for this component here
*/
export const mutations = {
select: (index: number) => {
mutations.clearSelected();
const images = elements.images();
if (images[index]) {
images[index].classList.add("selected");
}
},
clearSelected: () =>
elements.images().forEach(image => image.classList.remove("selected")),
toggleDropdownDisability: (disabled: boolean) => {
const dropdown = elements.dropdown();
dropdown && (dropdown.disabled = disabled);
},
applyFiltersToImages: (
filters: Array<{ index: number; filter: actions.Filter }>
) => {
elements.images().forEach((image, imageIndex) => {
const filterForImage = filters.find(f => f.index === imageIndex);
actions.filters.forEach(f => image.classList.remove(f));
filterForImage && image.classList.add(filterForImage.filter);
});
}
};
/**
* DOM listeners -> Redux actions
* Bridges all DOM events we are interested on and converts them to Redux actions.
*/
export const listeners = (dispatch: Dispatch<actions.ApplicationAction>) => ({
onImageSelect: () =>
elements
.images()
.map((image, index) =>
image.addEventListener("click", () =>
dispatch(actions.selectImage(index))
)
),
onFilterSelect: () => {
const dropdown = elements.dropdown();
dropdown &&
dropdown.addEventListener(
"change",
e =>
e.target &&
dispatch(actions.updateFilterOnSelected((e.target as any).value))
);
}
});
/**
* DOM elements references
* Always refetch dom elements to ensure existance at runtime
*/
const elements = {
images: () => {
const root = document.getElementById("some-dom-id");
const imageNodes = root && root.getElementsByTagName("img");
return imageNodes ? Array.from(imageNodes) : [];
},
dropdown: () =>
document.getElementById("filter-selection") as HTMLSelectElement | null,
regnerateImagesButton: () =>
document.getElementById("regenerate-images") as HTMLButtonElement | null,
clearFiltersAsyncButton: () =>
document.getElementById("clear-filters-async") as HTMLButtonElement | null
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment