3
I am studying about events in javascript, without using jQuery, and I came up with a question: how can I add / remove events with namespace
?
3
I am studying about events in javascript, without using jQuery, and I came up with a question: how can I add / remove events with namespace
?
2
One option is to use attributes in the element, and do everything with fields data-
, using selectors that add Event handlers to elements that have a certain data-
and keeping specific information thereon.
If you want to replicate the concept of jQuery namespace then an approximate idea could be like this:
(jsFiddle: http://jsfiddle.net/3hep98p6/)
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>
1
I liked the idea of @Sergio, but I was still not satisfied. I wish I could add events natives using namespaces. I continued searching and analyzing jQuery code again, but I continue not understanding the code for events.
I tried several times to simulate the namespaces until I came up with a functional script. I haven’t had the opportunity yet to test enough, but the idea is already working.
The logic is more or less the following. I create an array of objects in each element 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 with the element Node. So when I try to remove the event, I can search the elements targets by the events / namespaces I wish to remove.
I put the code I made on Jsfiddle for those interested in looking at the code.
Browser other questions tagged javascript events namespace
You are not signed in. Login or sign up in order to post.
And to remove, for example, events with the namespace
.something
, it is possible?– Oeslei
@Then all you need to do is wear
removeEventListener
and reference function. (http://jsfiddle.net/3hep98p6/1/)– Sergio