如何在Ember 2.1的JavaScript函数中调用同文件内的Ember Action?
Ember 2.1 同文件普通函数调用组件Action的解决方法
Ember组件的action绑定在组件实例上,文件作用域下的普通函数默认拿不到组件实例上下文,所以必须把组件实例作为参数传递给外部函数才能触发对应action,以下是两种可行实现:
方案1:传递组件实例给外部函数,使用标准send方法触发action
这是最符合Ember设计规范的写法,send方法会自动处理action冒泡、上下文绑定等内置逻辑,不会出现异常问题。
import Component from '@ember/component'; export default Component.extend({ // 示例:在组件的didInsertElement钩子中调用外部test函数 didInsertElement() { this._super(...arguments); // 调用test时把当前组件实例this作为参数传入 test(5, this); }, actions: { myAction() { console.log('myAction 被触发'); } } }); // 调整test函数,新增参数接收组件实例 function test(x, componentInstance) { // 调用组件send方法触发action,有传参需求时直接在action名后追加参数即可 componentInstance.send('myAction'); return 3 * x; }
注意:不要直接通过
componentInstance.actions.myAction()调用,这种写法跳过了Ember action的内置处理逻辑,容易出现上下文绑定错误、冒泡失效的问题。
方案2:将普通函数抽到组件内部方法(仅适用于函数只为当前组件服务的场景)
如果test函数不需要给其他模块复用,更建议直接放到组件内部作为自定义方法,不需要额外传递实例:
import Component from '@ember/component'; export default Component.extend({ didInsertElement() { this._super(...arguments); this.test(5); }, actions: { myAction() { console.log('myAction 被触发'); } }, // 把test作为组件的内部方法 test(x) { this.send('myAction'); return 3 * x; } });
内容的提问来源于stack exchange,提问作者Alexis K
相关产品推荐
相关产品推荐

