views:

108

answers:

2

In an earlier question I worked out how to store object as properties. Now I am trying to access those properties when the object is passed through an event but can't get it to work:

<script language="javascript">

  $(document).ready(function() {

    //create a TestObject
    function TestObject() {

      this.testProperty = "green";
    }

    //and an instance of it
    var testObject = new TestObject();

    //attach this instance to the div as a property
    var test;
    test = $('#test');//the div
    jQuery.data(test, "obj", testObject);


    //prove it worked and the TestObject is assigned
    alert(jQuery.data(test, "obj").testProperty);//works


    $('#test').click(TestClick);
    //test.click(TestClick); doesn't work either


    function TestClick() {

      alert($(this).attr("id"));//displays "test" - works

      alert(jQuery.data($(this), "obj").testProperty);
      //testProperty is null or not an object??
      //clearly TestObject is no longer attached to the div, why?
      //Or have I attached it the wrong way?    
      //alert(jQuery.data(this, "obj").testProperty); doesn't work either

    };


  });

</script>

<body>
    <form id="form1" runat="server">

    <div id="test">Here is a test div</div>

    </form>
</body>
+1  A: 

This will work for you, attach it to the element, not as a reference to the element which seems to change slightly (this is a different .data() call, see here for info):

$(document).ready(function() {
  function TestObject() {
    this.testProperty = "green";
  }

  var testObject = new TestObject();
  var test = $('#test').data("obj", testObject);

  alert(test.data("obj").testProperty);

  $('#test').click(TestClick);
  function TestClick() {
    alert($(this).attr("id"));
    alert($(this).data("obj").testProperty);
  };
});
Nick Craver
+1  A: 
//clearly TestObject is no longer attached to the div, why?

Because this returns your function context at this line alert(jQuery.data($(this), "obj").testProperty); you should use alert(jQuery.data($("#test"), "obj").testProperty); instead.

antyrat
That won't work either, in `jQuery.data()` you're storing a reference to the DOM element, which still isn't the same...in normal circumstances, you shouldn't use `jQuery.Data()`, but `.data()` instead.
Nick Craver