Response to statement
In this example, I update the pagination with fetch, and I have to bind addEventlistener to every page link.
Actually, in the example code it appears that elem.addEventListener()
is called on document.body
, not each link.
Variable Names
Some of the names are a bit misleading. For example target
is used to check the class name of elements. Therefore a better name might be targetClass
, target_class
, etc. Similarly, s
isn't very descriptive.
Feedback
Traversing DOM
Let's look at the findParent()
function:
window.findParent = function(child,filter,root) {
do {
if( filter(child)) return child;
if( root && child == root) return false;
} while(child = child.parentNode);
return false;
};
When would root
ever evaluate to a false
-y value? In the code above, document.body
is passed, so that seems unlikely.
It might be simpler to use a while
loop. Typically DOM traversing code I have seen would assign the child argument to a temporary variable (e.g. currentNode
) and assign the parent node to that variable until the target node is found or the root is reached.
window.findParent = function(child,filter,root) {
var currentNode = child;
while(root != currentNode) {
if (filter(currentNode )) {
return currentNode ;
}
currentNode = currentNode.parentNode;
}
return false;
}
This could also be re-written as a for
loop:
window.findParent = function(child,filter,root) {
for(var currentNode = child; root != currentNode; currentNode = curentNode.parentNode) {
if (filter(currentNode )) {
return currentNode ;
}
}
return false;
Over-complicated addEvent
The addEvent function creates two functions (i.e. evt
and cb
) which basically just call callback
passing the event object to the callback. These steps are superfluous. It could simply add the event listener, passing cb
to the listener
parameter:
window.addEvent = function(elem,type,callback) {
elem.addEventListener(type,callback,false);
return elem;
};
And does it need to return elem
? That would support chaining but your example code doesn't assign that return value to anything or have a subsequent call...
Simplification
This looks like a great application for an event delegate, unless there is some requirement I am missing about splitting out the functionality into those separate functions? See the example below, which adds the event handler to the root and then only calls the callback if the target of the event passes the filter.
function on(eventType, targetClass, callback) {
document.body.addEventListener(eventType, function (event) {
if (event.target.classList.contains(targetClass)) {
callback(event);
}
});
}
on("click", "page-link", function(e){
console.log("hey its working", e.target.innerHTML);
});
<h1>Header Text</h1>
<a class="page-link" href="javascript:void(0);">1</a>
<a class="page-link" href="javascript:void(0);">2</a>
<a class="page-link" href="javascript:void(0);">3</a>