Saturday, 31 August 2013

Store reference to another element on a jQuery object with the $.data()

Store reference to another element on a jQuery object with the $.data()

For my plugin, for simplifying the code (not as an absolute necessity) and
reducing unnecessary duplicate jQuery selector method calls, I wish to use
the $.data() jQuery method to link nodes together:
JavaScript
// This is all wrapped in a dom ready function
$('.main-nav > ul > li > a').each(function(edx, anchor){
var $anchor = $(anchor),
targetID = anchor.href, // eg. '#example-div-id'
$target = $(targetID);
// Bind together
$.data( $anchor, 'myTarget', $target );
$.data( $target, 'myTrigger', $anchor );
// Here a console.log() outputs the correct node for either of the above
// console.log( $.data( $target, 'myTrigger') );
//=> [<a href="#example-div-id">Example</a>]
});
// So that later in other methods I can use the following
// ... set $exampleTarget to a node depending on some state
var trigger = $.data( $exampleTarget, 'myTrigger' );
// Desired output of a console.log(trigger);
//=> [<a href="#example-div-id">Example</a>]
// Actual output
//=> undefined
So could someone please explain this behaviour regarding $.data().

No comments:

Post a Comment