ระบบเหตุการณ์ JavaScript อย่างง่ายสำหรับการโต้ตอบขั้นพื้นฐานกับองค์ประกอบ DOM
ระบบเหตุการณ์ทั้งหมดมีหนึ่งอินสแตนซ์หลักของคลาส SimplES เราสามารถแนบเหตุการณ์มากมายกับอินสแตนซ์นี้ตามที่เราต้องการ เราสามารถเพิ่มพวกเขาได้ที่อินสแตนซ์:
const blueSquare = document . querySelector ( '.blue-square' ) ;
const redSquare = document . querySelector ( '.red-square' ) ;
const eventSystem = new SimplES ( [
{
element : blueSquare ,
onEvent : function ( ) {
console . log ( "Clicked on blue square" ) ;
}
} ,
{
element : redSquare ,
onEvent : function ( ) {
console . log ( "Clicked on red square" ) ;
}
}
] ) ; และเมื่อใดก็ตามที่มีการสร้างอินสแตนซ์ด้วยวิธีการ หนึ่งในนั้นคือ attachEvent ซึ่งเพิ่มหนึ่งที่เรียกว่า event_pair ซึ่งเป็นวัตถุที่มีคุณสมบัติสองคุณสมบัติ element และ onEvent (คุณสมบัติเหล่านี้จะต้องตั้งชื่อเช่นนี้)
const blueSquare = document . querySelector ( '.blue-square' ) ;
const redSquare = document . querySelector ( '.red-square' ) ;
const eventSystem = new SimplES ( ) ;
eventSystem . attachEvent ( blueSquare , ( ) => console . log ( "Clicked on blue square" ) ) ;
eventSystem . attachEvent ( redSquare , ( ) => console . log ( "Clicked on red square" ) ) ; อีกวิธีหนึ่งในการเพิ่มเหตุการณ์คือการเพิ่มฟังก์ชั่นเดียวกันกับหลายองค์ประกอบ สิ่งนี้สามารถทำได้ด้วยวิธี attachWithSameFunction
const buttons = document . getElementsByClassName ( 'buttons' ) ;
const eventSystem = new SimplES ( ) ;
eventSystem . attachWithSameFunction ( buttons , ( ) => console . log ( "Clicked on one of these blue buttons!" ) ) ; เราสามารถเรียกเหตุการณ์เมื่อเป้าหมายของการคลิกไม่ได้อยู่ในเหตุการณ์ที่ลงทะเบียนกับ addEmptyClick โปรดทราบว่าการเรียกใช้วิธีนี้ทุกครั้งที่มีอินพุตที่ถูกต้องจะแทนที่เหตุการณ์ก่อนหน้านี้ สิ่งนี้มีประโยชน์เมื่อใด ตัวอย่างเช่นเมื่อหน้าเว็บมีปุ่มหลายปุ่มเช่นโพสต์บนเครือข่ายโซเชียล พวกเขามีปุ่มตัวเลือกที่เปิดกล่องโต้ตอบเล็ก ๆ น้อย ๆ แต่เราต้องการปิดมันเมื่อผู้ใช้คลิกไปที่ปุ่มอื่นหรือเมื่อเขา/เธอคลิกออกไปจากนั้นเราสามารถใช้วิธีนี้ได้
eventSystem . addEmptyClick ( ( ) => console . log ( "Here is nothing to click on!" ) ) ;PS: อย่าลังเลที่จะขยายห้องสมุดเล็ก ๆ นี้: D