0
点赞
收藏
分享

微信扫一扫

javascript设计模式-观察者

观察者

是一种管理人与任务之间的关系的得力工具,实质就是你可以对程序中某个对象的状态进行观察,并且在其发生改变时能够得到通知。一般有两种实现方式推或拉,在这个过程中各方的职责如下:

  • 订阅者可以订阅和退订,他们还要接收,并且可以在由人投送和自己收取之间进行选择;
  • 发布者负责投关,他们可以在送出和由人取之间进行选择;

function Publisher() {
    this.subscribers = [];
}
//投送方法
Publisher.prototype.deliver = function(data) {
    this.subscribers.forEach(
        function(fn) {
            fn(data);
        }
    );
    return this;
};
//订阅方法
Function.prototype.subscribe = function(publisher) {
    var that = this;
    var alreadyExists = publisher.subscribers.some(
        function(el) {
            if ( el === that ) {
                return;
            }
        }
    );
    if ( !alreadyExists ) {
        publisher.subscribers.push(this);
    }
    return this;
};
//退订方法
Function.prototype.unsubscribe = function(publisher) {
    var that = this;
    publisher.subscribers = publisher.subscribers.filter(
        function(el) {
            if ( el !== that ) {
                return el;
            }
        }
    );
    return this;
};

var publisherObject = new Publisher;
var observerObject = function(data) {
    // process data
    console.log(data);
    // unsubscribe from this publisher
    arguments.callee.unsubscribe(publisherObject);
};
observerObject.subscribe(publisherObject);

动画

// Publisher API
var Animation = function(o) {
  this.onStart = new Publisher,//三个可监视时刻
  this.onComplete = new Publisher,
  this.onTween = new Publisher;
};
Animation.
  method('fly', function() {
    // begin animation
    this.onStart.deliver();
    for ( ... ) { // loop through frames
      // deliver frame number
      this.onTween.deliver(i); 
    }
    // end animation
    this.onComplete.deliver();
  });

// setup an account with the animation manager
var Superman = new Animation({...config properties...});

// Begin implementing subscribers
var putOnCape = function(i) { };
var takeOffCape = function(i) { };

putOnCape.subscribe(Superman.onStart);
takeOffCape.subscribe(Superman.onComplete);

// fly can be called anywhere
Superman.fly();
// for instance:
addEvent(element, 'click', function() {
  Superman.fly();
});

事件监听器

var element = document.getElementById(‘a’);
var fn1 = function(e) {
  // handle click
};
var fn2 = function(e) {
  // do other stuff with click
};

addEvent(element, ‘click’, fn1);
addEvent(element, ‘click’, fn2);

举报

相关推荐

0 条评论