码迷,mamicode.com
首页 > Web开发 > 详细

Jquery的回调函数的使用

时间:2015-10-16 14:51:54      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

用$.Callbacks实现观察者模式

// 观察者模式
var observer = {
    hash: {},
    subscribe: function(id, callback) {
        if (typeof id !== ‘string‘) {
            return
        }
        if (!this.hash[id]) {
            this.hash[id] = $.Callbacks()
            this.hash[id].add(callback)
        } else {
            this.hash[id].add(callback)
        }
    },
    publish: function(id) {
        if (!this.hash[id]) {
            return
        }
        this.hash[id].fire(id)
    }
}
 
// 订阅
observer.subscribe(‘mailArrived‘, function() {
    alert(‘来信了‘)
})
observer.subscribe(‘mailArrived‘, function() {
    alert(‘又来信了‘)
})
observer.subscribe(‘mailSend‘, function() {
    alert(‘发信成功‘)
})
 
// 发布
setTimeout(function() {
    observer.publish(‘mailArrived‘)
}, 5000)
setTimeout(function() {
    observer.publish(‘mailSend‘)
}, 10000)

转:http://snandy.iteye.com/blog/1921793

 

Jquery的回调函数的使用

标签:

原文地址:http://www.cnblogs.com/hubing/p/4885035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!