Search code examples
javascriptiterationpuginline

why I can not use inline alert() in pug template if calling it from "if condition"?


I read in an article that I can use inline functions by defining them using - var = function(...){...}, but when I code:

    - var tryit = function tryit(tasks) {alert('will not work')};
    if tasks
          #adiv #{tryit(tasks)}

I get this error message:

if supervisor tryit is not a function

I scanned all pug documentation (well there is no such thing there, sure!), please tell me how I can have this approach, so that I could further process my variable 'tasks' sent from server in client side.
My use case is that if I have a json array from server, process it further and add a tree structure of DOM elements. Then finally append it to the div(id='adiv'). I can't anyway figure out how to do this, because when I use document.createElement(...) I get a similar error like the above with alert(..). I tried by script. but then I can't call the method I declared in script. in pug template with #{myScriptedFunc(...)}.
Edit:
What surprises me more: if I change it to:

- var tryit = function() {console.log('silence!');};
    if tasks
          #adiv #{tryit()}

There will be no error message, but the output will be in server side (in command line window where I run the server), not in the browser, meaning that the line was executed in server side? But I expected to have it run in client side. The way to do such a post-processing in client side is still a mistry to me.


Solution

  • Your variable should hold the 'name' of the function, the function itself should be anonymous.

    var tryit = function (tasks) {
      alert('will work')
    };
    

    so var tryit = function tryit(tasks) becomes var tryit = function(tasks)