zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    UART协议
    芯片时钟体系(take example as s3c2440)
    PCIe协议
    I2C协议
    SPI协议
    嵌入式相关术语列表
    TreeView控件数据绑定之:数据库数据递归绑定
    连接SQL Server 数据库的三种方式
    JS小功能之:五角星评论
    MVC学习之开发技巧总结(1)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5451825.html
Copyright © 2011-2022 走看看