简体   繁体   English

公共路由/控制器mxiin中的Ember访问控制器属性

[英]Ember access controller attribute within common route/controller mxiin

I have a attribute defined in my controller as 我在控制器中将属性定义为

myControllerAttr

Also there is a common mixin extended by both the route/controller ( my-mixin.js ) 路由/控制器( my-mixin.js )扩展了一个通用的mixin

Now in my-mixin.js, there are various methods which get called from both route/controller class 现在在my-mixin.js中,有两种方法可以从route / controller类中调用

My question is within these mixin methods, how do I access the controller attribute myControllerAttr 我的问题是在这些mixin方法中,如何访问控制器属性myControllerAttr

since this.myControllerAttr may not work always 由于this.myControllerAttr可能无法始终正常工作

It would depend on whether the method was invoked from a route or controller class 这取决于该方法是从路由类还是从控制器类调用的

Should I add an if condition OR what is the best way ? 我应该添加一个if条件,还是最好的方法是什么?

So to summarize, my question is how do I check between 综上所述,我的问题是如何检查

this.get('myControllerAttr') V/s
this.controllerFor(this.routeName).get('myControllerAttr')

Not sure if this is exactly what you need, but it might be. 不知道这是否正是您所需要的,但是可能是。

// 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
  }
})

And then you can use it like this: 然后您可以像这样使用它:

//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)
    }
  }
})

Here is a twiddle where I have implemented what I propose. 这里是一个玩弄 ,我已经实现了我的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM