convert all jquery scripts to live scripts - javascript

I have lot of jquery scripts which dont handle elements loaded or created on the fly, of course I can convert all my scrits and add the them the .live() function. However was wondering if there is any option or trick that could automatically simulate the live function in all the scripts without modifying them one by one manually.
Thanks for the comments , live is depreciated, so I restate my question with the .on() function.

There is not one trick that will make all existing event handler code work with dynamically loaded elements without updating each event handler unless you want to replace some jQuery methods with methods that work differently than jQuery has documented (not recommended). You would have to replace all jQuery event handling methods that you are currently using with methods that forced delegated event handling into them. This would be a bad way to do this. Not only would you be hacking jQuery into something that would be different than it is documented and opening yourself up to compatibility issues with other code, but you'd be forced into the most inefficient use of delegated event handling (which is why .live() was removed in the first place). Do not do this. Fix your code to use the proper method of delegated event handling. It's not hard at all.
.live() has been deprecated and even removed from the latest versions of jQuery. You should not use it. There is a form of .on() that will allow you to use delegated event handling for dynamically loaded objects. You can see how to use the proper form of .on() for dynamically loaded elements in this post: jQuery .live() vs .on() method for adding a click event after loading dynamic html.
The "proper" way to use .on() for dynamic elements is like this:
$('#parent').on("click", "#child", function() {});
where you select the closest parent to the dynamic element that is not itself dynamically loaded and bind the event handler to that element.
.live() was removed because it put all delegated event handlers on the document object somewhat analogous to this:
$(document).on("click", "#child", function() {});
If, however, you used a number of delegated event handlers like this, performance could start to bog down. That's because when you do it this way and you click anywhere in the document and that click bubbles up to the document, it has to compare every single selector in every single .live() event handler you had to the current clicked object. Since selector comparisons are not always fast, this could really bog down the processing of events.
When you place the event handler on an object closer to the actual object, you end up with far event handlers there and thus far fewer selectors to compare to and processing of the events works faster.
Here's a reference on some differences between static event handlers and delegated event handlers and some useful notes on them: JQuery Event Handlers - What's the "Best" method

Related

SAPUI5: How to bind a click event to horizontal layout?

Hi I'm developing my view in JS and I'm stuck in binding a click handler for my horizontal layout element. I've tried using Jquery
$("#myHorizontalLayout").bind("click",function(){window.alert()});
Which didn't work then I tried using attachPress with the element which obviously didn't exist. Please help.
Update:
The JS view is the default view of the application.
When on/bind does not work, it could be that the HTML of the control has actually not been created yet at this point in time. But even if you delay the binding, the re-rendering (re-creation of the HTML after changes) would remove your listener, at least when bound on the control itself.
A proper way of doing this is using the generic attachBrowserEvent function available on every control (here: on the layout) which internally handles all the rendering/rerendering stuff, see this example:
http://jsbin.com/hijutunefi/1/edit?html,output
attachBrowserEvent works for any browser event, as it attaches a new browser event listener to the root node of the control. For the most common browser events UI5 does event delegation, so for the "click" event and several others addEventDelegate can also be used, as pointed out by aborjinik.
Alternatively, listening on the <body> level with normal jQuery mechanisms should in general also work.
Which didn't work then I tried using attachPress with the element which obviously didn't exist. Please help.
Does this means that the element on which you are attaching event handler doesn't exists at this point? If this is the case you can hook the handler to some container, upper in the DOM hierarchy which you are sure that exists and filter the click events.
Example:
$("body").on("click", "#myHorizontalLayout", function(){
alert("Hey, you!");
});
As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document. For earlier versions, the
.bind() method is used for attaching an event handler directly to
elements. Handlers are attached to the currently selected elements in
the jQuery object, so those elements must exist at the point the call
to .bind() occurs.
Reference here
So try replacing bind with on and let me know if it works or not.

Trigger a change event for prototype.js with jQuery

I am dealing with a long prototype.js code that is activated by a 'change' event listener and I need to create a jQuery function that simulates a 'change' event to activate the prototype script. How can I do this?
note: $('select[id="..."]').val(...).trigger('change'); does not activate the prototype script
jQuery's .trigger() only works for event handlers added via jQuery (see: http://api.jquery.com/trigger/)
Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method.
Prototype's .fire() only works for custom events (see: http://api.prototypejs.org/dom/Event/fire/)
Fires a custom event of name eventName with element as its target. Custom events must include a colon (:) in their names.
Unfortunately, the only way to do what you're describing is to grab some kind of reference to the "long prototype.js code" and manually call it. (This would depend on what the implementation you are referring to looks like.) It's not possible to fire a true "native" change event using javascript.

Trigger Real Event with jQuery

It seems that jQuery's trigger() only runs event handlers that were bound with jQuery. I have some modules that use native browser event binding. Using the code from https://stackoverflow.com/a/2676527 works for me, but I'm wondering if there's something built in to jQuery that will do this?
Update from comments: apparently it works for click events on buttons. But not for change events on select boxes: http://jsfiddle.net/qxpXV/2/
For the record: hacking the other library to do its bindings with jQuery does make trigger() work, but I don't really want to do that.
You can do this by manually firing/dispatching an event (depending on the browser, fireEvent/dispatchEvent) directly on the DOM element. Code from this answer will handle the event dispatching, you'll just need to execute it against a DOM element and not the jQuery wrapper.

Are event listeners identical to html events?

Is onclick in HTML identical to .click() in jQuery?
Obviously they are identical from a usability standpoint, but I am curious how the browser handles them.
jQuery attaches events using JavaScript behind the scenes.
An important difference is that jQuery allows multiple events to be bound using click(), where as you can only attach one handler using onclick. This is because jQuery uses either addEventListener or attachEvent behind the scenes, as opposed to binding to .onclick directly.
Furthermore, attaching handlers via JavaScript (using jQuery or not) promotes unobtrusive JavaScript (i.e. not mixing JavaScript and HTML), which is a good thing.
No it's not the same. OnClick sets a property of a DOM element, where .click() adds an eventListener.
The differnce between them is that every DOM element can only have on property of a type at once. So if you use onClick= twice on an element, only last added will win, the first will be overwritten.
This will always alert 2, cause the first attachment will be overwritten:
myDiv.onclick = function(){alert('1')}
myDiv.onclick = function(){alert('2')}
Using .click() or .addEventListener('click', myFunction), you can add as many functions as you want. So the following will alert 1 and 2:
myDiv.click(function(){alert('1')})
myDiv.click(function(){alert('2')})
The differnt between jquerys .click() and .addEventListener() is, that the jquery solution works in all browser, cause IE<=8 has a different syntax (attchEvent). And that you can unbind all click handlers in once. The normal JavaScript solution can only detach the passed function not all of them.
(Noting that jQuery is a JavaScript library and so can't do anything that you couldn't do in JavaScript yourself if you had the time...)
The jQuery .click() method is different to onclick in a few key ways. In no particular order:
jQuery endeavours to normalise the event object so that you don't have to worry about the (mostly) minor differences between browsers
jQuery binds events with .addEventListener() or .attachEvent() depending on what your browser supports, so, again, you don't have to worry about the difference
jQuery guarantees that where multiple handlers have been bound for the same element and event they will be run in the order they were attached (noting that using .onclick you can only bind one handler anyway, but with .addEventListener() and .attachEvent() you can bind multiple handlers)
if you use jQuery's .on() or .delegate() (or the deprecated .live()) to attach events, rather than shortcut methods like .click(), it is easy to setup event delegation
Behind the scenes all the standard browser events are still happening, but jQuery provides a wrapper for them to make all of the above happen. Of course there are some other differences, but I see the above as the most important.
Obviously they are identical from a usability standpoint
No they're not. It would be much more accurate to say that jQuery's events are (almost) the same as .addEventListener() or .attachEvent() in how you use them, but even then as detailed above jQuery gives you an extra level of abstraction to save you having to code it all yourself.
the .click() even in JQuery is not the same. It is a piece of codes on top of the onclick in html. JQuery allows to bind methods to a event using this layer on top of the normal html events.
You can change/override .click() to adapt your needs. For instance when using a mobile browser or pda etc.

Should I remove events before changing a div content?

I've inherited a jQuery application that does its work by calling AJAX services without leaving the page.
There is a list of items, where when you click on an item the detail of the item is displayed, events attached to the buttons, then the html is disposed and new html will be created, new events attached and so on and so forth.
I was wondering whether JavaScript garbage collection will automatically clean up those events, or do they go in some Map like data structure and create a memory leak. Am I supposed to clean them up explicitly?
If you always bind the same events, you could also use something like jQuery live() or the likes instead of always binding/unbinding them.
Javascript garbage collection will not remove bound events to removed elements. jQuery functions often do depending on what method you use.
In example, .html() or .remove() will remove events and not leak memory. When in doubt you can always use .empty().
In my opinion the .live() discussion is fairly beside the point of memory leaks. The usage of .live() should be done when it makes sense from an architecture standpoint. Unless you need the event to be bound before the element is added to the DOM, or exist after the element is removed (because it may be added again) then .bind() is really the proper and faster method to use. .live() is slower than .bind() because each event must fire at the element, bubble to the document and then bubble back up to the element in order to be processed by .live(), while with .bind it can execute right away.
Also, FYI both .bind() and .live() are deprecated in the newest version of jQuery (1.7). They will still function, but the new syntax is .on(), using delegation to replace .live(). This is because too much .live() really slows down pages because each .live binds another event to the document which must be listened and processed every single event.
if you want to make it easier on the GC and not make him search if it has references , so you should unbind / die all events to the div.

Categories

Resources