Unbind events on elements that will be added to DOM later - javascript

I have a div with class="backdrop". This will be added to DOM when I click a button. To this is bound an event of 'wheel'.
I cannot avoid the binding of the event(happening through library) So i will want to unbind this globally.
I tried : $(".modal-backdrop.am-fade").unbind('wheel');
This works but I have to write this statement after each time the div is added to the DOM. I want something which I can write only once and would apply to all the divs which would be added to the DOM in future

I want something which I can write only once and would apply to all the divs which would be added to the DOM in future
If code in the library you're using is adding elements and binding events to them, you'll have to unbind them as you go, there's no alternative.
If you already have some way of triggering that (the library tells you when it adds a div), then you'll just have to have that code respond to that event.
If you don't already have some way of triggering it, you can use mutation observers to watch for the divs being added so you can unbind them. They're well-supported by modern browsers. Slightly less modern browsers may have sufficient support for the old mutation events that you can use a library that provides a mutation observer polyfill using mutation events (just search for "mutation observer polyfill"). Worst case, on really old browsers, you'll have to poll.
Of course, the best answer is to either stop using the library if it doesn't do what you want, or modify it (this is JavaScript, after all) so it doesn't do what you don't want.

Related

Alternative to Falsely Triggering an Event

TLDR Below
JS Fiddle To Demo
I've been really involved in recreating the tools that are foundations of premiere JS Libraries to better improve my skills. Currently I'm working on functional data-binding a la Angular.
The idea of data-binding is to take data and bind it to elements so that if manipulated all elements subscribed will change accordingly. I've gotten it to work but one thing I hadn't considered going into it was the issue with innerHTML vs value. Depending on the element you need to change one or the other( in the demo above you'll see that I needed to specifically single out the button element in a conditional statement because it has both, but that's kind of a fringe case )
The issue is that in order to capture a SPAN tag update I needed to trigger an event to happen, and the easiest one to manipulate for Text Boxes/Textareas was 'keyup'.
In my function then, if you pass in an element with no value property we assume you're going to be updating innerHTML, and we setup an observer to determine if the element ever mutates, and if it ever does, the observer will emit a 'keyup' event.
if (watchee.value == void(0)) {
var keyUpEvent = new Event('keyup');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
watchee.dispatchEvent(keyUpEvent);
});
});
observer.observe(watchee, {
childList: true
});
}
Now it may just be my paranoia, but it seems like I might be tunneling into a can of worms by faking 'keyup' on an element that doesn't natively have that support.
TLDR:
I'm curious if there's an alternative way to make, a.e. a span tag reactive other than faking a 'keyup'/'keydown'/'change' event? For instance, is there a way that I can make my own pure event(by pure I mean not reliant on other events) that checks if innerHTML or value has changed and then performs a function? I know that this is probably possible with a timer, but I feel like that might hinder performance.
EDIT: just an aside. In the demo the function called hookFrom works by taking a DOM node and returning a function that will take the receiving dom node and continues to return a function that will take additional receiving dom nodes. :
hookFrom(sender)(receiver);
hookFrom(sender)(receiver)(receiver2);
hookFrom(sender)(receiver)(receiver2)(receiver3)(receiver4)...(receiver999)...etc
JS Fiddle To Demo (same as above)
There is nothing inherently wrong with creating a similar event on a DOM node that doesn't natively have that functionality. In fact this happens in a lot of cases when trying to polyfill functionality for separate browsers and platforms.
The only issue with doing this sort of DOM magic is that it can cause redundancy in other events. For instance the example given in this article: https://davidwalsh.name/dont-trigger-real-event-names shows how a newly minted event using the same event name can cause problems.
The advice is useful, but negligible in this specific case. The code adds the same functionality between text boxes, divs, spans, etc... and they are all intentionally handled the same way, and if the event would bubble up to another event, it would be intentional and planned.
In short: There is a can of worms that one can tunnel into while faking already explicitly defined event names, but in this case, the code is fine!

jQuery: Use live event to add tabindex attributes

Would like all new elements with class .link to have a tabindex.
Delegate/Live does not seem to work:
$('body').delegate('.link', 'load', function(event){
$(this).attr('tabindex',0);
});
Trying to apply this to AJAX loaded elements. And using what I found in this answer, which suggests the "load" event may be possible.
I'd like to avoid using trigger, or modifying the AJAX callback.
The problem here is that no events are triggered when a new element is inserted into the DOM1. The "solution" (not the one you're looking for, unfortunately) is to set the tabindex from the complete callbacks of your ajax operations. You may use .ajaxComplete() to setup a global/default callback, but that may introduce new problems (such as having to deal with the order events are fired).
Well, that's not 100% accurate; there are the Mutation Events, which are not implemented consistently across different browsers, and are supposed to be replaced by Mutation Observers.

Possible to monitor when an image is being added/removed from a div?

If it's possible to somehow monitor a change in a div's DOM then that would be my solution - that will be enough to fire my event handler, but in case that's not possible - this is my problem:
I have a div, some javascript function (out of my control) will add or remove an image to this div (potentially nested in several divs/spans).
I need to attach an event (if possible using jQuery) that will fire when this particular image is added or not.
EDIT: To clarify - when I say added - I don't mean some sort of toggle of it's display attribute, I mean literally completely added or completely removed.
You can use the mutation events for that purpose. Be aware that some of those events are deprecated by now.
$('div').on( 'DOMSubtreeModified', function( event ) {
// something was changed
});
If you just need to know if some node was added, use
$('div').on( 'DOMNodeInserted', function( event ) {
// something was changed
});
The event object will give you further information about what exactly happend.
Since you asked for an alternative, there is the jQuery livequery plugin. AFAIK, i'll also use the Mutation Events if available, but it claims to be compatible with all browsers jQuery supports. That means, they will use a fallback solution (most likely intervall timers) to check for changes in incompatible browsers.
Further read: Mutation Events

Circumvent the DOMNodeInsertedIntoDocument event

Assume I have a javascript function createMyElement which returns a node that can be inserted into an HTML document.
In order to function properly, the code of the node created by createMyElement has to listen for events on the global document at least as soon as it is inserted in the document.
My first attempt was to add DOMNodeInsertedIntoDocument and DOMNodeRemovedFromDocument listeners to the node at creation time that add and remove the needed listener on document in turn.
However, the mutation events are deprecated by now (and don't seem to work reliably across browsers), so I am looking for a better solution.
Adding the listener for events at document at the creation time of the node would work. However, this doesn't seem to be a good solution as it would create memory and performance leaks: Even after the node was being removed from the document again and not needed anymore, the listener (and its references to the node) on the document would still persist.
Use a series of function callbacks or on-demand script callbacks to serialize the events.
Since I originally asked my question, the substitute for mutation events, namely mutation observers as defined in http://www.w3.org/TR/domcore/#mutation-observers, have been implemented in a number of browsers.
So a simple answer to my own question is to simply use mutation observers on the document to listen for nodes to be inserted or removed.
An even better way, however, is to use the new custom elements from https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/index.html, which gives one insertedCallbacks and removedCallbacks for custom elements.

live('click') and performance

I have a grid and there is a column which contains <a> anchor tag with some additional information in <data-..> tag and has a class name <class='myspeciallink'>. And in my unobtrusive JS script I select all the elements with that class name and apply live('click'). I need that to be live() because the grid gets generated in the runtime.
What happens inside the live('click') handler? I use that additional data and add a <div> to the page based on that data. Which in its turn used to generate jQuery UI dialog. It works great on my computer.
But! How could that work in real-world? Should I be bothered about possible performance implications? I feel that applying live() on more than a dozen elements instantaneously
would affect the performance. Especially with rather complicated handler like mine - it needs to get the data, parse the data, create a div, apply a dialog and etc.
Does that smell like a bad design? Could you suggest a different approach or my concerns are unfounded? Can I use some sort of a profiler tool to find the bottlenecks in my javascript?
UPD: Still nobody suggested any profiling tool. firebug and chrome dev tools are good, but maybe there is something even better?
live("click") is actually better up-front from a performance standpoint: Instead of binding an event handler to each matched element, you're applying a single event handler which waits for events to bubble up and then sees if the element that triggered the event matches the selector .live was called on.
Compare this to $('selector').click(...) which does loop over each element and bind a new event handler. live('click') has no additional overhead regardless of how many page elements match its selector. Depending on how many elements your selector matches, using .live can avoid a delay of up to a few seconds during the initial load of each page.
However, the event handler must check each event which bubbles up against its selector, to see if there is a match. This is going to add a small amount of overhead to every click event, but chances are very good that your users will not notice the difference.
Peter bailey also has a nice post about this: Performance difference between jQuery's .live('click', fn) and .click(fn)

Categories

Resources