【问题标题】:this is null in directive with es6这是 es6 指令中的 null
【发布时间】:2015-12-02 14:05:42
【问题描述】:

在类构造函数 angular 调用指令的链接函数后,我正在用 es6 编写指令(并用 babel 编译它),但由于某种原因,this 为空。

代码sn-p:

class AutoSaveDirective {
    constructor($timeout) {
        this.restrict = 'EA';
        this.require = '^form';

        this.$timeout = $timeout;
        this.scope = {
            autoOnSave: '&',
            autoSaveDebounce: '='
        }
    }

    link(scope, el, attr, formCtrl) {
        scope.$watch(()=> {
            console.log('form changed, starting timout');
            if (!formCtrl.$dirty) {
                return;
            }

at this line ==>if(this.currentTimeout){
                console.log('old timeout exist cleaning');
                this.currentTimeout.cancel();
                this.currentTimeout = null;
            }

            console.log('starting new timeout');
            this.currentTimeout = $timeout(()=>{
                console.log('timeout reached, initiating onsave')
                scope.autoOnSave();
            }, scope.autoSaveDebounce);
        });
    }
}

angular.module('sspApp').directive('autoSave', () => new AutoSaveDirective());

【问题讨论】:

    标签: angularjs angularjs-directive ecmascript-6 babeljs


    【解决方案1】:

    由于 Angular 调用它的方式,您必须将链接函数绑定到该类。

    class AutoSaveDirective {
        constructor($timeout) {
            //...
    
            this.link = this.unboundLink.bind(this);
        }
    
        unboundLink(scope, el, attr, formCtrl) {
            scope.$watch(()=> {
                //...
            });
        }
    }
    

    如果您想使用带角度的类,更好的方法是将它们用于控制器并使用 controllerAs 语法。例如

    angular.module('sspApp').directive('autoSave', function() {
        return {
            restrict: 'EA',
            scope: {
                autoOnSave: '&',
                autoSaveDebounce: '=',
                formCtrl: '='
            },
            bindToController: true,
            controller: AutoSave,
            controllerAs: 'ctrl'
        };
    });
    
    class AutoSave {
        constructor() {
            //Move logic from link function in here.
        }
    }
    

    【讨论】:

      【解决方案2】:

      link 函数由compile 函数返回,它作为函数调用,而不是作为方法调用。所以你可以定义一个compile 而不是link 方法:

      compile() {
        return (scope, el, attr, formCtrl)  => { ... };
      }
      

      话虽如此,将指令定义为类没有任何价值。

      【讨论】:

        猜你喜欢
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        • 2015-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多