Turk Turk - 1 year ago 74
Javascript Question

Accessing properties in objects created by constructors

I have a for loop like so:

for (var i = 0; i < 10; i++) {
obj[i] = new MapArea(some passed variables);

Now this constructor has a few predefined properties as well as some defined at initialization. As the for loop would suggest, each obj is held inside it's own index within the array obj[]. My issue is that after I have iterated through initialization, I cannot reference the properties of individual objects with a




The plugin I am building operates off mouse events (clicks and hovers) meaning I need to be able to check the obj attached to the event for specific properties on it's current state but have no way of programmatically knowing what index it is in the array to reference it, or at least doing so easily and concisely.

Has anyone encountered this problem and found a solution or am I pretty much forced into using the array and index as a reference? Any help would be awesome.

here is one of my methods for example:

$.fn.clickLight = function(options) {
var defaults = $.extend( {
color : "#43464B",
opacity : "0.3"
}, options);
ctx.globalAlpha = defaults.opacity;

$(area_ref).click(function(event) {
$(this).handleMouse(event).each(function() {
if (!$(this).clicked) { // I try and access here
$(this).clicked = true;
} else {
$(this).clicked = false;
} );
} );

$(area_ref).hover(function() {
$(this).handleMouse().each(function() {
} );
},function() {
if (!$(this).clicked){ // I try and access here
$(this).handleMouse().each(function() {
} );
} );
return $(this);

Answer Source

You can use the data function of jQuery to bind an object to a DOM element. So you can do something like the following to store your objects:

$('#clickableElement1').data('mapArea', new MapArea(some passed variables));

And something like the following to retrieve an object given an event:

var mapArea = $(event.currentTarget).data('mapArea');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download