代码之家  ›  专栏  ›  技术社区  ›  seawolf

在Riot中调用全局函数。js表达式

  •  0
  • seawolf  · 技术社区  · 9 年前

    我试图从Riot.js中的表达式调用在全局命名空间中声明的函数。

    这不起作用:

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

    可以 调用全局 moment() 函数(from moment.js):

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

    包含此函数的整个JavaScript文件 已加载…如果我从 this.on('mount') 它起作用:

    this.on('mount', function() {
        getDateString(new Date());
    });
    

    我真的不明白Riot的名字命名是如何运作的。js,所以我无法理解为什么我对getDateString()的调用在表达式中失败,但在mount函数中成功。有人能告诉我我做错了什么吗?

    1 回复  |  直到 9 年前
        1
  •  4
  •   Tsutomu Kawamura    9 年前

    确保您的 globalFunction() 声明为global。范围 <script> 标记定义中的标记不是全局的。小心点。

    <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>