* javascript自定义事件
var myEvent = document.createEvent("Event");
myEvent.initEvent("myEventName", true, true); var element = document.createElement("div");
element.addEventListener("myEventName", function(evt) {
console.log(evt);
// handle event
});
element.dispatchEvent(myEvent);
output:
Event {isTrusted: false, type: "myEventName", target: div, currentTarget: div, eventPhase: 2, …}
@Ref:
// Function synopsis
event.initEvent(eventType,canBubble,cancelable)
Usage:
function trigger(dom, event) {
var myEvent = document.createEvent('Event')
myEvent.initEvent(event, true, true);
dom.dispatchEvent(myEvent);
}
trigger(tab, "mouseover");
* 发布-订阅 模式
var salesOffices = {
clientList: [],
listen:function(fn) {
this.clientList.push(fn);
},
trigger: function() {
for (var i = 0, fn; fn = this.clientList[i]; i++) {
fn.apply(this, arguments);
}
return this;
}
}; // test
salesOffices.listen(function(price, squareMeter) {
console.log("price="+price);
console.log("squareMeter=" + squareMeter);
});
salesOffices.trigger(2000000,88).trigger(3000000,110);