mpen
mpen

Reputation: 282855

How to add object to jQuery object such that I can retrieve it later?

Example of what's happening:

> $('#start_date').dateTime = {bacon:5, myFunc: function() { ... }}
Object {bacon: 5, myFunc: function}
> $('#start_date').dateTime
undefined

I want to be able to retrieve my "bacon" object if I use the same selector.

I get that $() is returning a different object each time -- is there a workaround?

I know I can use .data, but the API isn't as nice. I'd have to do $('#start_date').data('dateTime').myFunc() instead of $('#start_date').dateTime.myFunc().

Upvotes: 2

Views: 66

Answers (3)

Terry Young
Terry Young

Reputation: 3531

Would you feel slightly better if you do this instead?

$('#start_date').data().dateTime.myFunc()


Alternatively, you can extend jQuery to make your life easier, or make jQuery work the way you like

Here I've whipped up a small plugin tailored for you so that you can pass in a dot-notation string to retrieve the data you want. In this case, it returns a function, so we can directly call it.

DEMO: http://jsfiddle.net/terryyounghk/8tWLn/

Plugin code

// Small plugin
$.fn.myData = function (namespace) {
    var namespaces = namespace.split('.'),
        data = this.data();
    $.each(namespaces, function (i, that) {
        data = data[that];
    });
    return data;
}

Usage Example

// set your data
$('#start_date').data('dateTime', {
    bacon:5, 
    myFunc: function() { 
        alert('mmm, bacon') 
    }
});


// call your function, note the dot notation
$('#start_date').myData('dateTime.myFunc')(); // better?

The philosophy here is, if we're constantly repeating stuff, there must be something stupid going on. Is there a way to extend jQuery to make life easier for me? You be the judge.

Personally, I don't prefer this plugin. I prefer my first suggestion if I am coding one-liners. But who knows? You might like the latter.

Upvotes: 2

zzzzBov
zzzzBov

Reputation: 179046

The jQuery way of associating data with a DOM element is to use the data method:

$('#start_date').data('dateTime', {bacon:5, myFunc: function() { ... }});

once you've set the data, you can call:

baconTime = $('#start_date').data('dateTime');
baconTime.myFunc();

As far as the API is concerned, it's consistent with the rest of the jQuery api, where the accessor version is:

$(...).method(key);

and the mutator version is:

$(...).method(key, value);

Upvotes: 1

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

You can add the property to DOM element, instead of jQuery object:

$('#start_date')[0].dateTime = {bacon:5};
console.log($('#start_date')[0].dateTime);

Or you can maintain some kind of dictionary with selectors as keys. However, the calling would still be not very stylish and values are not connected with DOM:

//for example save your data by id attribute
DOMData[$('someselector').attr('id')].dateTime = {bacon: 5}; 

Upvotes: 1

Related Questions