【问题标题】:Ember isController V/s isRoute V/s isComponentEmber isController V/s isRoute V/s isComponent
【发布时间】:2016-06-10 13:51:19
【问题描述】:

我有一个从不同地方(路由/控制器/组件)触发的方法的通用混合

我的问题是准确识别“this”上下文的最佳方法是什么(即调用是否来自路由/控制器/组件)

我有这个

isRoute: Ember.computed('target', function() {
        const isUndefined = typeof this.get('target') === 'undefined'
        return isUndefined ? true : false
    }),

    isController: Ember.computed('target', function() {
        const isUndefined = typeof this.get('target') === 'undefined'
        return isUndefined ? false : true
    }),

但是,即使对于组件,isController 也会返回 true。所以它不是唯一的标识。

我需要一种准确的方法来唯一标识所有 3 个。

【问题讨论】:

    标签: javascript jquery ember.js


    【解决方案1】:

    我会建议不同的地方使用不同的 mixin,然后通过使用另一个对象在 mixins 之间共享公共代码,而不是那样做。允许您在不将参议院代码混合在一起的情况下做您想做的事情。

    【讨论】:

      【解决方案2】:

      你可以这样接近

      ../Mixin.js

      Ember.Mixin.create({
          actions :{
      
              identifyFromLocation: function(isFromController, isFromRoute, isFromComponent) {
                  if (isFromController) {
                      //Do Process here if from controller
                  }
                  if (isFromModel) {
                      //Do Process here if from Model
                  }
                  if (isFromComponent) {
                      //Do Process here if from component
                  }
              }
          }
      });
      

      ../route.js

      Ember.Route.extend({
          actions: {
              sendToMixin() : function () {
                  this.send('identifyFromLocation', false, true, false)
              }
          }
      });
      

      ../component.js

      Ember.Component.extend({
          actions: {
              sendToMixin() : function () {
                  this.send('identifyFromLocation', false, false, true)
              }
          }
      });
      

      ../controller.js

      Ember.Controller.extend({
          actions: {
              sendToMixin() : function () {
                  this.send('identifyFromLocation', true, false, false)
              }
          }
      });
      

      【讨论】:

      • 谢谢。请问我做isRoute,isController的方式是否不是一种安全的识别方式。您对此有什么问题吗?
      • 另外我如何在 3 个地方触发 sendToMixin ?
      【解决方案3】:

      我认为验证某物是否是控制器的相对节省方法就是使用instanceof

      if(this instanceof Ember.Controller) {...}
      

      这也适用于路由和组件。

      【讨论】:

      • 非常感谢..所以它也会唯一标识组件吗?
      猜你喜欢
      • 2015-09-13
      • 2016-01-22
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      相关资源
      最近更新 更多