jsコンポーネント化チームが開発したカスタムイベントデモ
4393 ワード
本demoはdivマウスドラッグ事件で、先端の経験があるものは全部分かります.
// : , ( )
window.onload = function () {
var d1 = new Drag();
d1.init({ //
id: 'div1'
});
var d2 = new Drag();
d2.init({ //
id: 'div2'
});
bindEvent(d2, 'toDown', function () {
document.title = 'hello';
});
bindEvent(d2, 'toDown', function () {
document.body.style.background = 'black';
});
var d3 = new Drag();
d3.init({ //
id: 'div3'
});
bindEvent(d3, 'toDown', function () {
document.title = ' ';
});
bindEvent(d3, 'toUp', function () {
document.title = ' ';
});
var d4 = new Drag();
d4.init({ //
id: 'div4'
});
bindEvent(d4, 'toUp', function () {
document.title = 'byebye';
});
};
function Drag() {
this.obj = null;
this.disX = 0;
this.disY = 0;
this.settings = { //
};
}
Drag.prototype.init = function (opt) {
var This = this;
this.obj = document.getElementById(opt.id);
extend(this.settings, opt);
this.obj.onmousedown = function (ev) {
var ev = ev || window.event;
This.fnDown(ev);
fireEvent(This, 'toDown');
document.onmousemove = function (ev) {
var ev = ev || window.event;
This.fnMove(ev);
};
document.onmouseup = function () {
This.fnUp();
fireEvent(This, 'toUp');
};
return false;
};
};
Drag.prototype.fnDown = function (ev) {
this.disX = ev.clientX - this.obj.offsetLeft;
this.disY = ev.clientY - this.obj.offsetTop;
};
Drag.prototype.fnMove = function (ev) {
this.obj.style.left = ev.clientX - this.disX + 'px';
this.obj.style.top = ev.clientY - this.disY + 'px';
};
Drag.prototype.fnUp = function () {
document.onmousemove = null;
document.onmouseup = null;
};
function bindEvent(obj, events, fn) {
//obj :
//events :
//fn :
obj.listeners = obj.listeners || {};
obj.listeners[events] = obj.listeners[events] || [];
obj.listeners[events].push(fn);
if (obj.nodeType) {
if (obj.addEventListener) {
obj.addEventListener(events, fn, false);
}
else {
obj.attachEvent('on' + events, fn);
}
}
}
function fireEvent(obj, events) { //
if (obj.listeners && obj.listeners[events]) {
for (var i = 0; i < obj.listeners[events].length; i++) {
obj.listeners[events][i]();
}
}
}
function extend(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
}
・