gpt4 book ai didi

javascript - 从模板调用时不会注入(inject) EmberJS 第二级服务

转载 作者:行者123 更新时间:2023-12-03 06:03:31 24 4
gpt4 key购买 nike

当从模板调用服务函数时,例如onClick={{action myFirstLevel.hello}},应注入(inject)到myFirstLevel的服务保持未定义

通过组件操作的调用正在工作。

<button onClick={{action myFirstLevel.hello}}>Hello Service</button>
<button onClick={{action 'hello'}}>Hello Action</button>


App = Ember.Application.create();

App.MyFirstLevelService = Ember.Service.extend({
mySecondLevel: Ember.inject.service(),
hello: function() {
console.log('Hello first level');
this.get('mySecondLevel').hello();
}
});

App.MySecondLevelService = Ember.Service.extend({
hello: function() {
console.log('Hello second level');
}
});

App.MyButtonComponent = Ember.Component.extend({
myFirstLevel: Ember.inject.service(),

actions: {
hello: function() {
this.get('myFirstLevel').hello();
}
}
});

http://emberjs.jsbin.com/conaxaheno/1/edit?html,js,console,output

最佳答案

myFirstLevel.hello 函数将通过 MyButtonComponent 此上下文调用,因此当您在服务中执行 this.get('mySecondLevel') 时它将返回 undefined,因此要使其正常工作,您应该将 mySecondLevel 服务包含到组件中

App.MyButtonComponent = Ember.Component.extend({
myFirstLevel: Ember.inject.service(),
mySecondLevel: Ember.inject.service(),
actions: {
hello: function() {
this.get('myFirstLevel').hello();
}
}
});

关于javascript - 从模板调用时不会注入(inject) EmberJS 第二级服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39644086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com