【问题标题】:how to create a global function in meteor template如何在流星模板中创建全局函数
【发布时间】:2015-06-04 13:17:02
【问题描述】:

如何为流星中的所有模板创建一个函数?

index.js

// Some function
function somefunction(){
  return true;
}

Test1.js

Template.Test1.events({
  'click button' : function (event, template){
    //call somefunction
  }
});

Test2.js

Template.Test2.events({
  'click button' : function (event, template){
    //call some function
  }
});

【问题讨论】:

标签: meteor meteor-blaze meteor-helper


【解决方案1】:

您需要使您的函数成为一个全局标识符,以便能够跨多个文件调用它:

index.js

// Some function
somefunction = function(){
  return true;
};

在 Meteor 中,变量默认是文件范围的,如果你想将标识符导出到全局命名空间以在你的项目中重用它们,你需要使用这个语法:

myVar = "myValue";

在 JS 中,函数是可以存储在常规变量中的字面量,因此语法如下:

myFunc = function(){...};

【讨论】:

    【解决方案2】:

    如果您不想乱扔全局名称空间,您可以创建单独的文件:

    导入/函数/somefunction.js

    export function somefunction(a,b) {
        return a+b;
    }
    

    并在模板的逻辑中导入并以这种方式使用:

    客户端/calculations.js

    import { somefunction } from '../imports/functions/somefunction.js'
    
    Template.calculations.events({
        'click button' : function (event, template){
            somefunction(); 
        }
    });
    

    也许这不是你想要的,因为在这种情况下你应该在任何模板中附加导入,但避免全局变量是相当好的做法,并且可能你不想在 任何模板。

    【讨论】:

      【解决方案3】:

      它不需要位于代码的任何特定部分。如果它在另一个文件中,对于全局函数,即 global.js,只需从模板 .js 文件中导入它并照常调用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-08
        • 2017-03-07
        • 2018-04-27
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 2015-12-24
        • 2012-05-17
        相关资源
        最近更新 更多