views:

161

answers:

1

I'm trying to use jQuery's data() function to store and retrieve data on an element. I want to retrieve the data stored in a textarea whenever the user enters the space bar1. However, everytime I do this I get undefined back from data().

Now, if I define exactly the same Javascript in the HTML, it works as expected. Is there some "gotcha" to data() that keeps it from working in GreaseMonkey?

Here is the GreaseMonkey script:

(function(){
  //boilerplate greasemonkey to wait until jQuery is defined...
  function GM_wait()
  {
    if(typeof unsafeWindow.jQuery == 'undefined') {
      window.setTimeout(GM_wait,100);
    } else {
      var $ = unsafeWindow.jQuery;
      $(function() { letsJQuery($); });
    }
  }
  GM_wait();

  function letsJQuery($)
  {
    //store the data initially
    $('textarea[name=comment]').data('tst', 'abc');

    //retrieve the data on spacebar
    $('textarea[name=comment]').live('keypress', function(e) {
      if(e.which == 0x20) { //spacebar
        alert("the stored data is: " + $(this).data('tst'));
        return false;
      }
    });
  }
})();

And here is my very simple test HTML file:

<html>
<head>
<script type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
</head>
<body>
<textarea name="comment"></textarea>
</body>
</html>


1 This is a very simplified version of my problem, of course.

+1  A: 

The following should work:

  function letsJQuery($)
  {
    //store the data initially
    var ta = $('textarea[name=longtext]').data('tst', 'abc');

    //retrieve the data on spacebar
    ta.live('keypress', function(e) {
      if(e.which == 0x20) { //spacebar
        alert("the stored data is: " + ta.data('tst'));
        return false;
      }
    });
  }
micahwittman
I'm curious: Can you describe why this code works, and the submitter's code does not? They look to me like they should do the same thing.
Luke Dennis
Inside the function passed to the live method, the implicit variable this is apparently not functioning correctly regarding the jQuery data method (at least inside Greasemonkey). There's more investigation to be done to determine why. One solution that works (at least with the given code example in the OP) is to use the data method from a variable that's not being set based on this inside the function. What I've show here is var ta scoped outside the method. You could also set the ta var inside the function - right above the alert line would work.
micahwittman