Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自定义事件 #1

Open
gamebody opened this issue Jul 13, 2016 · 0 comments
Open

自定义事件 #1

gamebody opened this issue Jul 13, 2016 · 0 comments

Comments

@gamebody
Copy link
Owner

gamebody commented Jul 13, 2016

闲话少说,直接看代码

var Event = {

    //订阅列表
    eventList: [], 

    //添加订阅
    addEvent: function(fn) {
        this.eventList.push(fn)
    },

    //触发订阅
    fire: function() {
        for(var i = 0, fn;fn = this.eventList[i++];) {
            fn.apply(this, arguments);
        }
    }
}

Event.addEvent(function(day, con) {
    console.log(day + '是' + con);
})

Event.fire('星期三', '雨天');

上面我们实现了一个'简短'的发布订阅模式,可以看到我们通过这种自定义事件,很方便的可以注册事件函数,触发事件函数。可能还没有实际领率到这种设计模式的好处,不着急,慢慢往下看。

通用的自定义事件

var event = {
    eventlist: { },
    //工具函数
    index: function(arr, key) {
        var l = arr.length;
        var i = 0;
        for(i; i < l; i++) {
            if (arr[i] === key) {return i}
            else { return -1 }
        }
    },
    on: function(type, fn) {
        if(!this.eventlist[type]) {
            this.eventlist[type] = [];
        }
        this.eventlist[type].push(fn);
        return this;
    },
    fire: function(type) {
        var args = Array.prototype.slice.call(arguments, 1) || [];
        var fns = this.eventlist[type];
        var i = 0;
        var len = fns.length;
        for(i; i < len; i++) {
            fns[i].apply(this, args);
        }
        return this;
    },
    off: function(type, fn) {
        if(!type && !fn) {this.eventlist = {}}
        if(type && !fn) {delete this.eventlist[type]}
        if(type && fn) {
            var fns = this.eventlist[type];
            var index = this.index(fns, fn);
            fns.splice(index, 1);
        }
    }
}

原理是一样的,下面做个小栗子看下怎么运用。

小栗子

    <button id="btn">点击</button>
    <input type="text" id="input" value="haha">
    <div id="container"></div>
_event.on('show', function(text) {
    con.innerHTML = text;
})
btn.addEventListener('click', function(){
    var text = input.value;
    _event.fire('show',text);
})

可以看到自定义事件可以在不同的模块间传递信息,这种设计模式在很多的场合是很有用的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant