2

I tried to define a javascript function in the global block of my ruleset, but when I try to run the function I get 'f() is not defined'.

global {
  emit <|
    function f() { return 42 };
  |>;
}

rule use_function {
  select when pageview ".*"
  { 
    emit <| result=f(); console.log("The value is "+result+"."); |>;
  }
}

What do I need to do to make my function callable?

Randall Bohn
  • 2,597
  • 2
  • 16
  • 20
  • 1
    Your code seems to be working fine for me. I get the right result. Are you still having this problem? – Steve Nay Jan 11 '11 at 17:06
  • OK I guess I oversimplified my example. I set up a simple link with href="javascript:f()". The way I got that working was to stick the function on KOBJ and then call "javascript:KOBJ.f()" – Randall Bohn Jan 11 '11 at 20:51
  • I would edit your question or ask a new one asking how to call a JavaScript function declared inside KRL from outside a KRL closure. – Mike Grace Jan 12 '11 at 03:21

1 Answers1

2

Your code should be working.

Here is another example similar to yours that is working for me.

ruleset a60x535 {
  meta {
    name "function-scope-test"
    description <<
      function-scope-test
    >>
    author "Mike Grace"
    logging on
  }

  global {
    emit <|
      function showMeTheMoney() {
        alert("42!");
        return 42;
      }
    |>;
  }

  rule call_global_function {
    select when pageview ".*"
    {
      emit <|
        var amount = showMeTheMoney();
        alert("amount: "+amount);
        function cool() {
          alert("yes");
        }
      |>;
    }
  }
}

Results of running app on example.com with bookmarklet: alt text alt text

When KRL generates JavaScript to run on the browser's page it puts the code in closures which can create some unexpected behavior. In your code and my example the emitted JavaScript runs in the same scope so the function calls have access to each other. If you have JavaScript watching for a button click which then calls a function emitted in the global block you may have issues with the click function not being in the same scope as the global emitted JavaScript function.

Mike Grace
  • 16,636
  • 8
  • 59
  • 79