views:

977

answers:

3

I'm trying to pass story_id into the innermost inline function, but its always 0 even though its not 0 in the outer function. How do I pass this value in?

function activateSearch(){
  if($('story_filter')) Event.observe('story_filter', 'keyup',
    function(event) {
      $('stories_table').select(".story").each(
        function(story) {
          story_id = story.id.split('_')[1];
          story.select('.tableCell', '.indexCardContent').each(
            function(task, story_id) {
              hideStoryRow(story_id);
              task_filter = new RegExp($F('story_filter'), "i");
              if (task.innerHTML.match( task_filter ))
              {
                  showStoryRow(story_id);
                  throw $break;
              }
            }
          );
        }
      );
    }
  );
}
A: 

you've got a scoping issue.

quick fix: define story_id as a global.

var story_id;

function activateSearch() { ....
Chad Grant
Variable `story_id` *is* already global, as it was introduced here without the `var` statement.
Török Gábor
Would have been a better question if you had show that in your example code or explained that.
Chad Grant
A: 

You don't. The each method takes the function definition and then calls that function for each element in the Array. You'd need to write your own custom each method if you wanted to use the inline funtion definition.

For both readability and functionality, I would break out the inner most inline function and then for each element in the list, call out to your function.

Justin Niessner
+6  A: 

All you have to do to make this work is change this line:

    function(task, story_id) {

to this:

    function(task) {

You don't have to pass story_id anywhere -- it's already in scope in the inner function!

Jason Orendorff