[AngularJS] Design Pattern: Simple Mediator

We're going to use rootScope emit here to send out events and then we're going to listen for them in the run block. We're going to use rootScope on down in the run block to listen for the same event that we sent out to the system.

 

angular
    .module('app', [])
    .controller('MainCtrl', function($scope, Order) {
        $scope.newOrder = function() { new Order(); };
    })
    .factory('Order', function($emit) {
        function Order() {
            this.email   = 'brett.shollenberger@gmail.com';
            this.product = 'Macbook Pro';
            $emit('order:created', this);
        }
        return Order;
    })
    .factory('$emit', function($rootScope) {
        return function() { $rootScope.$emit.apply($rootScope, arguments); };
    })
    .factory('Email', function($window) {
        function Email(text) {
            $window.alert(text);
        }
        return Email;
    })
    .run(function($rootScope, Email) {
        $rootScope.$on('order:created', function(event, order) {
            new Email('Email sent to ' + order.email + ' for ' + order.product);
        });
    });

 

We don't want ot inject $rootscope into Order factry, so we use mediator to create a $emit() function, and each time we create a new order, it will send the create event to run block. isnide the run block we send the email. This is good because, the order doesn't know the Email event, it onlys emits a create event.

 

转载于:https://www.cnblogs.com/Answer1215/p/5451825.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值