JSFiddle - React, Tailwind, and code Playground
HTML
<div id="blah">blah</div>
<a>something</a>
JavaScript
(function() {
var selectorsBound = [],
objectsBound = [],
undefined;
function getIndex(obj) {
return $.inArray(obj, objectsBound);
}
$.fn.bindObj = function(data) {
var index = getIndex(data),
selector = this.selector;
if (!selector && this.length) {
selector = this.get(0);
}
if (index !== -1) {
$(selectorsBound[index]).unbindObj(data);
}
selectorsBound.push(selector);
objectsBound.push(data);
return this;
}
$.fn.unbindObj = function(data) {
var selector = this.selector,
index,
selectorIndex;
if (!selector && this.length) {
selector = this.get(0);
}
if (!data) {
index = $.inArray(selector, selectorsBound);
if (index !== -1) do {
this.unbindObj(objectsBound[index]);
index = $.inArray(selector, selectorsBound);
} while (index !== -1);
} else {
index = getIndex(data);
if (index !== -1 && index === $.inArray(selector, selectorsBound)) {
objectsBound.splice(index, 1);
selectorsBound.splice(index, 1);
}
}
return this;
}
$.retrieve = function(obj) {
var index = getIndex(obj);
if (index !== -1) {
return $(selectorsBound[index]);
}
return jQuery('');
}
})();
$(function() {
var myObject = {
blorg: 'shmorg'
};
$('a').bindObj(myObject);
console.log($.retrieve(myObject)); // logs $('a')
$('div').bindObj(myObject);
console.log($.retrieve(myObject)); // logs $('div')
$('div').unbindObj(myObject);
$(document.getElementById('blah')).unbindObj();
console.log($.retrieve(myObject)); // logs empty jQuery...