我有一个属性在我的控制器中定义为
myControllerAttr
此外,还有一个由路由/控制器(my-mixin.js
)扩展的公共混入
现在,在my-mixin.js中,有从路由/控制器类调用的各种方法
我的问题是在这些混合方法中,如何访问控制器属性myControllerAttr
因为this.myControllerAttr
可能并不总是有效
这将取决于该方法是从路由还是控制器类调用的
我应该添加一个if条件,还是最好的方法是什么?
总而言之,我的问题是如何在
this.get('myControllerAttr') V/s
this.controllerFor(this.routeName).get('myControllerAttr')
发布于 2016-05-07 14:05:13
不确定这是否是您所需要的,但它可能是。
// mixins/type-checker.js
export default Ember.Mixin.create({
isRoute: computed('target',function(){
const isUndefined = typeof this.get('target') === 'undefined'
return isUndefined ? true : false
}),
isController: computed('target',function(){
const isUndefined = typeof this.get('target') === 'undefined'
return isUndefined ? false : true
}),
getAttribute(attr){
let attrYouWant
if(this.get('isController')){
attrYouWant = this.get(attr)
}else{
attrYouWant = this.controllerFor(this.routeName).get(attr)
}
return attrYouWant
}
})
然后你可以像这样使用它:
//routes/application.js
import TypeChecker from '../mixins/type-checker'
export default Ember.Route.extend(TypeChecker, {
actions: {
test(){
const testProp = this.getAttribute('prop')
console.log(testProp)
}
}
})
这是一个twiddle,我在其中实现了我提出的建议。
https://stackoverflow.com/questions/37069952
复制