导入一个函数来使用它所调用的作用域

时间:2016-10-06 13:18:32

标签: meteor

使用Meteor,我试图在模板的范围内使用一个文件中的函数放在另一个文件中。我尝试使用箭头功能:

第一个文件:

export const myFunc = ()=>{
    console.log(this.x);
};

第二档:

import {myFunc} from './myFunc.js';

Template.MyTemplate.onCreated(function(){
    this.x = 4;
    myFunc(); //undefined
});

使用未在模板本身定义的函数影响模板变量的最佳方法是什么? (我也需要其他模板的那些功能)

1 个答案:

答案 0 :(得分:1)

如何将模板的变量作为参数传递给函数? 将它与使用ReactiveVar相结合,您可以在myFunc中设置它们

import { myFund } from './myFunc.js'

Template.MyTemplate.onCreated(function () {
  this.myVar = new ReactiveVar('Foo');
});

Template.myTemplate.onRendered(function() {
  myFunc(this.myVar);
  console.log(this.myVar.get())  // 'Bar'
});

并在您的函数文件中

export const myFunc = (myVar) => {
  //Use myVar
  myVar.set('Bar')
};