首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Riot.js表达式中调用全局函数

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

Stack Overflow用户
提问于 2015-08-30 17:04:31
回答 1查看 1.7K关注 0票数 0

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

这样做是行不通的:

代码语言:javascript
复制
<strong>Created { getDateString(item.created) } by { item.creator }</strong>

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

代码语言:javascript
复制
<strong>Created { moment(item.created) } by { item.creator }</strong>

包含此函数的整个JavaScript文件被加载.如果我从getDateString()调用this.on('mount'),它可以工作:

代码语言:javascript
复制
this.on('mount', function() {
    getDateString(new Date());
});

我真的不明白名称空间在Riot.js中是如何工作的,所以我不知道为什么我对getDateString()的调用在表达式中失败,而在挂载函数中成功。有人能告诉我我做错了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-31 21:12:04

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

代码语言:javascript
复制
<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>
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32299073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档