AngularJS中介者模式实例

在任何应用程序中,中介者模式随处可见。

→ 有一个事件源,触发事件,传递参数
→ 中介者记下这个事件,向外界广播,并带上参赛
→ 有一个地方侦听中介者事件,一旦事件源触发事件,就从中介者手里获取事件相关参数

本篇,要体验的是在AngularJS中的中介者模式。

场景是:当创建一个订单,需要引发一些动作,比如给用户发邮件等。

AngularJS中有没有相关的方法呢?

--有,$emit方法用来向上级Scope广播事件,$on方法用来侦听事件。

首先在$rootScope层面封装一个中介者。

.factory('$emit', function($rootScope) {
    return function() { $rootScope.$emit.apply($rootScope, arguments); };
})

有一个定单,把创建定单看作是事件源,创建定单的时候,让中介者记下事件名称,并带上参数。

//创建一个Order实例,也是事件源
.factory('Order', function($emit) {
    function Order() {
        this.email   = 'brett.shollenberger@gmail.com';
        this.product = 'Macbook Pro';
        $emit('order:created', this);
    }
    return Order;
})

让$rootScope侦听中介者的事件名称。

.run(function($rootScope, Email) {
    //让$rootScope侦听事件
    $rootScope.$on('order:created', function(event, order) {
        new Email('Email sent to ' + order.email + ' for ' + order.product);
    });
});


以上,Email在$rootScope侦听到order:created事件调用回调函数后使用到,这里用来弹出窗口。

//创建一个Email实例,弹出窗口显示信息
.factory('Email', function($window) {
    function Email(text) {
        $window.alert(text);
    }
    return Email;
})

controller中提供一个函数用来创建定单实例。

.controller('MainCtrl', function($scope, Order) {
    //产生一个新订单
    $scope.newOrder = function() { new Order(); };
})

前端就是调用:

<a class="btn btn-lg btn-primary" role="button" ng-click="newOrder()">Place new order</a>


完整代码如下:

angular
    .module('app', [])
    .controller('MainCtrl', function($scope, Order) {
        //产生一个新订单
        $scope.newOrder = function() { new Order(); };
    })
    .factory('$emit', function($rootScope) {
        return function() { $rootScope.$emit.apply($rootScope, arguments); };
    })
    //创建一个Order实例,也是事件源
    .factory('Order', function($emit) {
        function Order() {
            this.email   = 'brett.shollenberger@gmail.com';
            this.product = 'Macbook Pro';
            $emit('order:created', this);
        }
        return Order;
    })
    //创建一个Email实例,弹出窗口显示信息
    .factory('Email', function($window) {
        function Email(text) {
            $window.alert(text);
        }
        return Email;
    })
    .run(function($rootScope, Email) {
        //让$rootScope侦听事件
        $rootScope.$on('order:created', function(event, order) {
            new Email('Email sent to ' + order.email + ' for ' + order.product);
        });
    });
原文地址:https://www.cnblogs.com/darrenji/p/5162355.html