首页 > ES6中 修饰器的使用场景?

ES6中 修饰器的使用场景?

rt
在看阮一峰的es6入门过程中注意到有这么一个特性,感觉挺像c#里面的语法。
哪位同学在实际开发中用过,一般在什么场景下推荐使用呢?
谢谢了


Angular2 使用了 Decorator


装饰器实际上就是wrapper的语法糖


像AngularJS中的依赖注入: 写的一个Inject装饰器: 地址:https://github.com/hjzheng/es...

function inject(...list) {
    return function(target) {
        target.$inject = list;
    };
}

// http://technologyadvice.github.io/es7-decorators-babel6/
// make babel 6 support decorators
import './todo.css';

@inject('$log', 'ToDoResource')
class TodoListController {
    constructor($log, ToDoResource) {
        this.todos = [];
        this.$log = $log;
        this.ToDoResource = ToDoResource;
        this.init();
    }

    addTodo() {
        if (this.todoText) {
            this.todos.push({text: this.todoText, done: false});
            this.ToDoResource.save({text: this.todoText, done: false});
            this.$log.info('add new Todo: ' + this.todoText);
        }
    }

    removeTodo(id) {
        this.ToDoResource.delete({id: id}, data => {
            if (data.success) {
                this.todos.splice(id, 1);
            }
        });
    }

    remaining() {
        return this.todos.filter(todo => todo.done === false).length;
    }

    mark(index, todo) {
        this.ToDoResource.update({id: index}, todo);
    }

    archive() {
        let dones = this.todos.filter(todo => todo.done);
        dones.forEach((todo, index) => {
            this.removeTodo(index);
        });
        this.todos = this.todos.filter(todo => !todo.done);
    }

    init() {
        this.ToDoResource.list(list => {
            this.todos = list;
        });
        this.$log.info('init');
    }
}

// TodoListController.$inject = ["$log"];

export default TodoListController;

推荐AngularJS的ngParty写的一组AngularJS2的装饰器 https://github.com/ngParty/ng...

【热门文章】
【热门文章】