Skip to content

Instantly share code, notes, and snippets.

@mertenvg
Created March 12, 2013 10:08
Show Gist options
  • Save mertenvg/5141727 to your computer and use it in GitHub Desktop.
Save mertenvg/5141727 to your computer and use it in GitHub Desktop.
Persist jQuery objects with its corresponding node so that additional values set on the object itself are maintained. Usage: // persist the jQuery object with the dom node (if one is persisted already then the new is ignored) $(selector).persist$(); // or override and existing persisted object $(selector).persist$(true); // then retrieve the per…
(function ($) {
var objCollection = [];
$.fn.persist$ = function (override) {
var current = this.data('oid');
if (typeof current === 'undefined') {
var next = objCollection.length;
objCollection.push(this);
this.data('oid', next);
}
else if (override) {
objCollection[current] = this;
}
return this;
};
$.fn.get$ = function () {
var current = this.data('oid');
if (typeof current === 'undefined') {
return this;
}
return objCollection[current];
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment