Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Saturday, February 11, 2012

Differences Between jQuery .bind() vs .live() vs .delegate() vs .on()


Using the Bind Method


The .bind() method registers the type of event and an event handler directly to the DOM element in question. This method has been around the longest and in its day it was a nice abstraction around the various cross-browser issues that existed.

The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.

Pros
  • This methods works across various browser implementations.
  • It is pretty easy and quick to wire-up event handlers.
  • The shorthand methods (.click().hover(), etc...) make it even easier to wire-up event handlers.
  • For a simple ID selector, using .bind() not only wires-up quickly, but also when the event fires the event handler is invoked almost immediately.

Cons
  • The method attaches the same event handler to every matched element in the selection.
  • It doesn't work for elements added dynamically that matches the same selector.
  • There are performance concerns when dealing with a large selection.
  • The attachment is done upfront which can have performance issues on page load.

Using the Live Method


The .live() method uses the concept of event delegation to perform its so called "magic". The way you call .live() looks just like how you might call .bind(), which is very convenient. However, under the covers this method works much different. The .live method attaches the event handler to the root level document along with the associated selector and event information. By registering this information on the document it allows one event handler to be used for all events that have bubbled (a.k.a. delegated, propagated) up to it. Once an event has bubbled up to the document jQuery looks at the selector/event metadata to determine which handler it should invoke, if any. This extra work has some impact on performance at the point of user interaction, but the initial register process is fairly speedy. 

The good thing about this code as compared to the .bind() example above is that it is only attaching the event handler once to the document instead of multiple times. This not only is faster, but less wasteful, however, there are many problems with using this method and they are outlined below.

Pros
  • There is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method.
  • The upgrade path from .bind() to .live() is very small. All you have to do is replace "bind" to "live".
  • Elements dynamically added to the DOM that match the selector magically work because the real information was registered on the document.
  • You can wire-up event handlers before the document ready event helping you utilize possibly unused time.

Cons
  • This method is deprecated as of jQuery 1.7 and you should start phasing out its use in your code.
  • Chaining is not properly supported using this method.
  • The selection that is made is basically thrown away since it is only used to register the event handler on the document.
  • Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document.
  • Since all selector/event information is attached to the document once an event does occur jQuery has match through its large metadata store using the matchesSelectormethod to determine which event handler to invoke, if any.
  • Your events always delegate all the way up to the document. This can affect performance if your DOM is deep.

Using the Delegate Method


The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored. Just like the .live() method, this technique uses event delegation to work correctly. 

If you skipped over the explanation of the .live() method you might want to go back up and read it as I described some of the internal logic that happen.
The .delegate() method is very powerful. The above code will attach the event handler to the unordered list ("#members") along with the selector/event information. This is much more efficient than the .live() method that always attaches the information to the document. In addition a lot of other problematic issues were resolved by introducing the .delegate() method. See the following outline for a detailed list.

Pros
  • You have the option of choosing where to attach the selector/event information.
  • The selection isn't actually performed up front, but is only used to register onto the root element.
  • Chaining is supported correctly.
  • jQuery still needs to iterate over the selector/event data to determine a match, but since you can choose where the root is the amount of data to sort through can be much smaller.
  • Since this technique uses event delegation, it can work with dynamically added elements to the DOM where the selectors match.
  • As long as you delegate against the document you can also wire-up event handlers before the document ready event.

Cons
  • Changing from a .bind() to a .delegate() method isn't as straight forward.
  • There is still the concern of jQuery having to figure out, using the matchesSelectormethod, which event handler to invoke based on the selector/event information stored at the root element. However, the metadata stored at the root element should be considerably smaller compared to using the .live() method.

Using the On Method


Did you know that the jQuery .bind().live(), and .delegate() methods are just one line pass throughs to the new jQuery 1.7 .on() method? The same is true of the .unbind(),.die(), and .undelegate() methods.

Pros
  • Brings uniformity to the various event binding methods.
  • Simplifies the jQuery code base and removes one level of redirection since the .bind(),.live(), and .delegate() call this method under the covers.
  • Still provides all the goodness of the .delegate() method, while still providing support for the .bind() method if you need it.

Cons
  • Brings confusion because the behavior changes based on how you call the method.

Tuesday, November 8, 2011

Reading local files in JavaScript

HTML5 finally provides a standard way to interact with local files, via the File API specification. As example of its capabilities, the File API could be used to create a thumbnail preview of images as they're being sent to the server, or allow an app to save a file reference while the user is offline. Additionally, you could use client-side logic to verify an upload's mimetype matches its file extension or restrict the size of an upload.
The spec provides several interfaces for accessing files from a 'local' filesystem:
  1. File - an individual file; provides readonly information such as name, file size, mimetype, and a reference to the file handle.
  2. FileList - an array-like sequence of File objects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
  3. Blob - Allows for slicing a file into byte ranges.
When used in conjunction with the above data structures, the FileReader interface can be used to asynchronously read a file through familiar JavaScript event handling. Thus, it is possible to monitor the progress of a read, catch errors, and determine when a load is complete. In many ways the APIs resemble XMLHttpRequest's event model.
Note: At the time of writing this tutorial, the necessary APIs for working with local files are supported in Chrome 6.0 and Firefox 3.6. As of Firefox 3.6.3, the File.slice() method is not supported.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Sunday, June 5, 2011

The Tree Slider

The new HTML5 History API (which really has nothing to do with HTML — it's a JavaScript API) allows us to manage the URL changes while CSS3 transitionshandle the sliding. Permalinks are always maintained, your back button works as expected, and it's much faster than waiting for a full page load.


https://github.com/blog/760-the-tree-slider

Saturday, December 11, 2010

Apple Removes Jailbreak API From iOS 4.2


Apple has removed its built in methods to help developers detect jailbroken devices from iOS 4.2, according to NetworkWorld.
This detection API let the MDM applications in effect ask the operating system if it had been compromised. Jailbreak exploits typically change a number of operating system files, and exploit one or another low-level OS features to let users directly load their own or third-party applications.
Previously, developers had created their own series of operating system checks to detect jailbreak.
"We used it when it was available, but as an adjunct," says Joe Owen, vice president of engineering at Sybase, which offers the Afaria device management software. "I’m not sure what motivated their removing that….I’ve not had anyone [at enterprise customer sites] talk to me about this API being present or being removed."
In July of this year the Library of Congress deemed that jailbreaking your iPhone in order to install applications not approved by Apple and/or to unlock is legal.

http://www.iclarified.com/entry/index.php?enid=13170
http://www.networkworld.com/news/2010/121010-apple-ios-jailbreak.html

Tuesday, March 9, 2010

Quick Tip: Fully Understanding $.grep()

The jQuery method $.grep() is one of those methods that isn’t used as often as it should be. This is mostly because, until you understand exactly what it does, it can be a bit confusing. Hopefully, this video quick tip will explain when and why you would use it.

At its core, $.grep is a simple little method that will filter through an array and sift out any items that don’t pass a particular control. For example, if we have an array of the numbers 1-10, and want to filter out any values that are below 5, we can do:

var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

nums = $.grep(nums, function(num, index) {
// num = the current value for the item in the array
// index = the index of the item in the array
return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

Or let’s say that you have an array of numbers and strings, and you want to sift out all of the strings, leaving just an array of numbers. One way that we can accomplish this task is with $.grep.

var arr = '1,2,3,4,five,six,seven,8,9,ten'.split(',');

arr = $.grep(arr, function(item, index) {
// simply find if the current item, when passed to the isNaN,
// returns true or false. If false, get rid of it!
return !isNaN(item);
});

console.log(arr); // 1,2,3,4,8,9

For further training, be sure to refer to the jQuery API.

http://net.tutsplus.com/tutorials/php/quick-tip-fully-understanding-grep/

Monday, December 22, 2008

FireBug Console API

Firebug adds a global variable named "console" to all web pages loaded in Firefox. This object contains many methods that allow you to write to the Firebug console to expose information that is flowing through your scripts.

http://getfirebug.com/console.html