Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chrismarksus/21c83cfe1e02e720eb97ab563e9cfcb4 to your computer and use it in GitHub Desktop.
Save chrismarksus/21c83cfe1e02e720eb97ab563e9cfcb4 to your computer and use it in GitHub Desktop.
_Separate DOM Manipulation methods from Functional methods

_Separate DOM Manipulation methods from Functional methods

This is an example of how you might separate method with side-effects from pure functions. This make the not only the pure function testable but the methods with side-effect are more general purpose and become more of a utility method that is easier to test

A Pen by Chris Marks on CodePen.

License.

<p id="js-text-area">Add Text Here</p>
<button id="js-add-text">Click Me!</button>
<button id="js-reset-text">Reset</button>
/* DOM manipulation methods */
/**
* Set the html/text of a DOM element by paassing an id and string to the method
*
* id - string - The id of the dome element
* html - string - The text and or html string to add the DOM
*/
function setDomText(id, html){
try {
let el = document.getElementById(id);
el.innerHTML = html;
} catch(err){
throw err;
}
}
/**
* Add a click listener to a DOM element by ID string
*
* id - string - The id of the dome element
* func - function - A function to attach to the DOM element
*/
function setOnClick(id, func){
try {
let el = document.getElementById(id);
el.addEventListener("click", func, false);
} catch(err){
throw err;
}
}
/*
Functional code that can be separated and unit tested. The methods above can stubbed
or mocked in the unit test for the code below.
*/
/**
* Reset the the DOM element to the previous text
*/
function resetTextArea(){
setDomText("js-text-area","Add Text Here");
}
/**
* Add new test to the DOM element
*/
function addTextToDomHandler(){
setDomText("js-text-area", "<span style='color: darkred;'>Test adding text and html to the dom!</span>");
}
/* These are the method that you might add to a main.js file or the stript tag */
/**
* Add click listener to the add text button
*/
setOnClick("js-add-text", addTextToDomHandler);
/**
* Add click listener to the reset button
*/
setOnClick("js-reset-text", resetTextArea);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment