Mike
Mike

Reputation: 637

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

this.propertyName;

or

$(this).propertyName;

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
        console.log(obj.this.clicked);
        $(this).highlight(defaults.color);
        $(this).clicked = true;
      } else {
        console.log(this.clicked);
        $(this).clearlight();
        $(this).clicked = false;
      }
    } );
  } );

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

Upvotes: 0

Views: 57

Answers (1)

mm759
mm759

Reputation: 1424

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');

Upvotes: 1

Related Questions