I am studying about events in javascript without using jQuery, and I had a question: how can I add / remove events with namespace
?
I am studying about events in javascript without using jQuery, and I had a question: how can I add / remove events with namespace
?
I liked the idea of @Sergio, but I still was not satisfied. I wish I could add events using namespaces. I continued searching and analyzed the jQuery code again, but I continue not understanding the code for the events.
I tried several times to simulate the namespaces until I came up with a functional script. I have not had the opportunity yet to test enough, but the idea is already working.
The logic is more or less as follows. I create an array of objects in each element that I add events to. These objects have the added event, namespaces, and function.
[
{
event: 'click',
namespaces: [
'someting',
'else'
],
handler: function
}
]
The array is directly associated to the node of the element. So when I try to remove the event, I can search the elements events / namespaces that I want to remove.
I put the code I made in JSFiddle for anyone interested in looking at the code.
An option is to use attributes in the element, and do everything with data-
fields, using selectors that add event handlers to elements that have a certain data-
and saving specific information there.
If you want to replicate the concept of jQuery namespace then an approximate idea might look like this:
(jsFiddle: link )
function acionar(target, type) {
var doc = document;
var event;
if (doc.createEvent) {
event = new Event(type);
target.dispatchEvent(event);
} else {
event = doc.createEventObject();
target.fireEvent('on' + type, event);
}
};
var p = document.querySelector("p");
p.addEventListener("test.something", function (event) {
alert(event.type + ' - ' + this.innerHTML);
});
document.querySelector("button").addEventListener('click', function (event) {
acionar(p, "test.something");
});
<button>Carrega aqui para disparar um evento no elemento "p"</button>
<p>cobaia</p>