2016-09-22 39 views
0

從模板調用服務功能時,例如, onClick={{action myFirstLevel.hello}},應注入的服務myFirstLevel停留undefinedEmberJS從模板進行呼叫時不會注入第二級服務

通過組件動作的調用正在工作。

<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

回答

1

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(); 
    } 
    } 
}); 
0

你可以使用黑客。但是,除非您絕對必須這樣做,否則不推薦使用它。我相信,在您的情況的最佳方法是使用第二個按鈕選項,但你可以把你的機會,如果你對你在做什麼絕對的把握:

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

此功能會居然叫你的時候單擊該按鈕,但它將與組件的上下文一起調用,而不是您想要的組件的上下文,因爲目標this您改爲訪問組件作用域。

另一種選擇是

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

在這裏面,你會避免與業主搞亂,但它仍然是完全不可讀。您可以做的最好的事情就是堅持在組件範圍上定義操作並從您的模板中調用它們。這些操作反過來可以爲你提供任何深度和觸發功能。

0

@kumkanillam是對的,上下文是錯誤的。要設置它,可以使用target=,但它似乎不適用於onClick=...

因此正確synthax是<button {{action myFirstLevel.hello target=myFirstLevel}}>Hello Service</button>

https://github.com/emberjs/ember.js/issues/14334