问题描述:

I am trying to call a function declared in the global namespace from an expression in Riot.js.

This does not work:

<strong>Created { getDateString(item.created) } by { item.creator }</strong>

I can call the global moment() function (from moment.js):

<strong>Created { moment(item.created) } by { item.creator }</strong>

The overall JavaScript file containing this function is loaded... if I call getDateString() from this.on('mount') it works:

this.on('mount', function() {

getDateString(new Date());

});

I don't really understand how namespacing works in Riot.js, and so I can't figure out why my call to getDateString() is failing in the expression but succeeding in the mount function. Can someone tell me what I'm doing wrong?

网友答案:

Make sure your globalFunction() is declared at global. The scope of <script> tag inside the tag definition is not global. Take care about it.

<my-tag>
  <p>{ someGlobalFunction(message) }</p><!-- will work -->
  <p>{ localFunction1(message) }</p><!-- won't work -->
  <p>{ localFunction2(message) }</p><!-- will work -->
  <p>{ localFunction3(message) }</p><!-- will work -->

  <script>
    this.message = 'world'

    // Not reachable from the template
    function localFunction1 (arg) {
      return 'Hello ' + arg + '!'
    }

    // Reachable because this is the same as localFunction3
    localFunction2 (arg) {
      return 'Hello ' + arg + '!'
    }

    // Reachable from the template
    this.localFunction3 = function(arg) {
      return 'Hello ' + arg + '!'
    }.bind(this)
  </script>
</my-tag>
网友答案:

Copy/paste mistake, I was passing a variable that didn't exist and Javascript didn't know how to do that. Once I changed the parameter, the function was called as expected.

相关阅读:
Top