Trình xử lý sự kiện so với trình xử lý sự kiện javascript

Cho đến nay, chúng tôi đã làm việc với các thuộc tính xử lý sự kiện để xử lý các sự kiện trong mã của chúng tôi. Các thuộc tính này đại diện cho các sự kiện cho đối tượng mà nó thuộc về [một phần tử HTML, đối tượng

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
6 hoặc
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
0]. Một sự kiện chỉ là một tín hiệu cho thấy điều gì đó đã xảy ra trong trình duyệt. Để sử dụng một thuộc tính xử lý sự kiện, chúng ta đặt giá trị của nó cho một hàm và mỗi khi sự kiện tương ứng xảy ra, hàm đó sẽ được gọi và tất cả mã bên trong hàm sẽ chạy. Bằng cách này, chúng tôi sử dụng các thuộc tính của trình xử lý sự kiện để viết mã phản ứng với các sự kiện xảy ra trong trang web của chúng tôi

Trong bài học này, chúng ta sẽ học một phương pháp xử lý sự kiện mới. chúng tôi sẽ tạo trình xử lý sự kiện trong mã của mình để lắng nghe và phản ứng với các sự kiện xảy ra trong trang web của chúng tôi. Quá trình này được gọi là lắng nghe sự kiện và nó thực hiện mọi thứ mà các thuộc tính trình xử lý sự kiện của chúng ta thực hiện, nhưng nó có một lợi thế khiến việc lắng nghe sự kiện trở thành phương pháp xử lý sự kiện ưa thích

Lưu ý rằng xử lý sự kiện thực sự là một thuật ngữ chung mô tả các quy trình và công cụ mà nhà phát triển sử dụng để viết mã đáp ứng các sự kiện. Trong phát triển web, xử lý sự kiện bao gồm các thuộc tính của trình xử lý sự kiện, khái niệm lắng nghe sự kiện với trình xử lý sự kiện và hình thức xử lý sự kiện đã lỗi thời với các thuộc tính trình xử lý sự kiện HTML

Hãy đi sâu vào khái niệm mới về lắng nghe sự kiện

Vậy làm cách nào để tạo một trình lắng nghe sự kiện? . Hãy xem một ví dụ sử dụng dự án Mad Libs. Trước đây chúng tôi đã sử dụng thuộc tính trình xử lý sự kiện

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
1 để phản ứng với sự kiện gửi trên biểu mẫu của chúng tôi. Đây là đoạn mã chúng tôi sẽ làm việc với

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  form.onsubmit = function[event] {
    // omitted code to get the value for each form input
    ...
    // omitted code to set the story variables to the values we got from the form
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  };
};

Xin lưu ý rằng chúng tôi đã bỏ sót một số mã, mã lấy giá trị đầu vào của biểu mẫu và đặt giá trị cho câu chuyện Mad Libs của chúng tôi. Bất cứ khi nào chúng tôi bỏ mã, chúng tôi sẽ sử dụng dấu chấm lửng

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
2 ở vị trí của nó. Chúng tôi chỉ muốn tập trung vào thuộc tính trình xử lý sự kiện cho sự kiện gửi biểu mẫu và tìm hiểu cách sử dụng trình xử lý sự kiện thay thế. Kiểm tra mã được cập nhật của chúng tôi bên dưới — thay đổi lớn nhất khi sử dụng trình xử lý sự kiện là sử dụng phương thức tích hợp sẵn thay vì thuộc tính

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};

Hãy chia nhỏ mã mới này

  • Chúng tôi gọi phương thức
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    3 trên đối tượng
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    4 của chúng tôi để tạo trình lắng nghe sự kiện. Cũng giống như các thuộc tính xử lý sự kiện, chúng tôi nhắm mục tiêu đối tượng mà chúng tôi muốn đính kèm trình xử lý sự kiện vào. Quá trình này thường được gọi là đăng ký trình lắng nghe sự kiện
  • Chúng tôi chuyển hai đối số cho phương thức
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    3
    • // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      6 là đối số đầu tiên. Đối số đầu tiên này là tên của sự kiện mà chúng tôi muốn nhắm mục tiêu và kiểu dữ liệu của nó luôn là một chuỗi. Nó không có
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      7 thông thường mà chúng tôi thêm vào thuộc tính trình xử lý sự kiện của mình. Ở đây, chúng tôi chỉ tham khảo tên của sự kiện
    • Đối số thứ hai là một hàm. Đây được gọi là hàm xử lý được gọi và chạy khi sự kiện tương ứng xảy ra. Bạn có thể ngạc nhiên rằng hàm có thể là đối số giống như chuỗi và số nhưng đây thực sự là một tính năng rất mạnh của JavaScript. Trong mã ví dụ của chúng ta, chúng ta đang sử dụng cụ thể một biểu thức hàm ẩn danh, nhưng thay vào đó, chúng ta có thể sử dụng các loại hàm khác ở đây, chẳng hạn như khai báo hàm [chúng ta sẽ xem các ví dụ về điều này trong các bài học sau]
    • Lưu ý rằng đối số thứ hai này thường được gọi là hàm gọi lại, là bất kỳ hàm nào được truyền vào một phương thức hoặc lệnh gọi hàm dưới dạng đối số. Chúng ta sẽ tìm hiểu thêm về các cuộc gọi lại sau trong bài học này
  • Chúng tôi đóng trình lắng nghe sự kiện bằng
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    8
    • Với dấu ngoặc nhọn đóng
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      9, chúng ta sẽ đóng hàm mà chúng ta chuyển vào làm đối số thứ hai
    • Với dấu đóng ngoặc đơn
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      20, chúng tôi đang đóng cuộc gọi phương thức
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      3
    • Với dấu chấm phẩy
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      22, chúng ta tuân theo quy ước JS bằng cách thêm dấu chấm phẩy vào cuối câu lệnh
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      23, trong đó dấu chấm lửng
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      2 đại diện cho hai đối số mà chúng ta chuyển vào phương thức lắng nghe sự kiện của mình

Chúng tôi sử dụng cùng một phương thức

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3 cho bất kỳ trình lắng nghe sự kiện nào mà chúng tôi muốn thiết lập. Thay đổi sự kiện mà chúng tôi đang nhắm mục tiêu là vấn đề thay đổi đối số đầu tiên mà chúng tôi chuyển vào phương thức
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
26. Hãy xem một ví dụ khác. Lần này, chúng tôi sẽ cập nhật thuộc tính trình xử lý sự kiện
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
27 của mình để sử dụng trình xử lý sự kiện thay thế

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
2

Giống như trong ví dụ ban đầu của chúng tôi, chúng tôi đã gọi phương thức

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3 của mình trên đối tượng
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
0, chuyển vào chuỗi
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  form.onsubmit = function[event] {
    // omitted code to get the value for each form input
    ...
    // omitted code to set the story variables to the values we got from the form
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  };
};
30 làm đối số đầu tiên để nhắm mục tiêu sự kiện tải và một biểu thức hàm ẩn danh làm đối số thứ hai làm trình xử lý sự kiện. Cuối cùng, chúng tôi đã đảm bảo đóng lệnh gọi phương thức
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3 của mình sau khi kết thúc biểu thức hàm đóng bằng chuỗi dấu ngoặc đóng, dấu ngoặc đơn và dấu chấm phẩy
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
8

Vì chúng tôi đã thực hành tốt với các thuộc tính trình xử lý sự kiện, biểu thức hàm và sử dụng các phương thức đối tượng, nên việc chuyển sang sử dụng trình xử lý sự kiện sẽ giúp chúng tôi thoải mái hơn. Mọi thứ chúng tôi đã học về nhắm mục tiêu các đối tượng cụ thể [như

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
0,
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
6 hoặc đối tượng phần tử HTML] để đính kèm trình xử lý sự kiện vẫn không thay đổi với trình xử lý sự kiện. Điều tương tự cũng xảy ra với các loại sự kiện mà chúng ta có thể nhắm mục tiêu

Ngoài ra, tất cả các thuộc tính "một sự kiện" có thể được dịch dễ dàng sang cú pháp mà chúng tôi sử dụng để nhắm mục tiêu các sự kiện với trình xử lý sự kiện. chỉ cần xóa "bật" khỏi thuộc tính sự kiện và biến nó thành một chuỗi. Hãy xem thêm một số ví dụ

  • Thuộc tính trình xử lý sự kiện
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      form.onsubmit = function[event] {
        // omitted code to get the value for each form input
        ...
        // omitted code to set the story variables to the values we got from the form
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      };
    };
    
    35 là sự kiện
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      form.onsubmit = function[event] {
        // omitted code to get the value for each form input
        ...
        // omitted code to set the story variables to the values we got from the form
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      };
    };
    
    36 trong trình xử lý sự kiện của chúng tôi
  • Thuộc tính trình xử lý sự kiện
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      form.onsubmit = function[event] {
        // omitted code to get the value for each form input
        ...
        // omitted code to set the story variables to the values we got from the form
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      };
    };
    
    37 là sự kiện
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      form.onsubmit = function[event] {
        // omitted code to get the value for each form input
        ...
        // omitted code to set the story variables to the values we got from the form
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      };
    };
    
    38 trong trình xử lý sự kiện của chúng tôi
  • Thuộc tính trình xử lý sự kiện
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      form.onsubmit = function[event] {
        // omitted code to get the value for each form input
        ...
        // omitted code to set the story variables to the values we got from the form
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      };
    };
    
    39 là sự kiện
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    20 trong trình xử lý sự kiện của chúng tôi

Bây giờ chúng ta hãy chuyển sang những lợi thế của việc sử dụng trình lắng nghe sự kiện. Sau đó, chúng tôi sẽ xem xét thêm thông tin về chức năng gọi lại

Lợi ích của việc sử dụng Trình lắng nghe sự kiện

Sự khác biệt chính giữa thuộc tính trình xử lý sự kiện và trình xử lý sự kiện là có thể thêm [hoặc xóa] nhiều trình xử lý sự kiện khi chúng ta học trong một bài học khác bằng cách sử dụng trình xử lý sự kiện. Điều này có nghĩa là đối với một sự kiện trên cùng một đối tượng [thường là một phần tử HTML], chúng ta có thể đăng ký nhiều trình xử lý sự kiện

Hãy xem một ví dụ. Trong ví dụ này, chúng tôi sẽ mở rộng trang web Mad Libs của mình bằng cách thêm chức năng mới vào trang web. Giả sử chúng tôi không chỉ muốn trình xử lý sự kiện gửi của mình nhận các giá trị biểu mẫu cho câu chuyện Mad Libs mà còn hiển thị một nút mới đặt lại biểu mẫu và kích hoạt cảnh báo bằng quảng cáo [yuck. ]. Bây giờ chúng tôi có 3 phản ứng khác nhau đối với sự kiện gửi mà chúng tôi cần xử lý trong mã của mình. Hãy xem cách chúng tôi sẽ làm điều này với người nghe sự kiện

Trước tiên, chúng ta cần thêm một nút mới vào HTML của mình. Chúng tôi sẽ thêm nó ngay bên dưới thẻ đóng

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  form.onsubmit = function[event] {
    // omitted code to get the value for each form input
    ...
    // omitted code to set the story variables to the values we got from the form
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  };
};
3

Chúng tôi cũng đã bao gồm thẻ

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
21 trước nút mới để tạo ngắt dòng

Lưu ý rằng thuộc tính

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
22 trên nút được đặt thành
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
23. Giá trị thuộc tính này làm cho nút không có hành vi mặc định và không làm gì khi được nhấn. Chúng tôi có thể nhắm mục tiêu một sự kiện nhấp chuột trên một nút bằng
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
24, nhưng không phải là một sự kiện gửi biểu mẫu, vì vậy chúng tôi không thể sử dụng
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
24 trong một thành phần nút trong biểu mẫu HTML

Điều này trái ngược với cài đặt

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
26 trên phần tử nút, có nghĩa là được sử dụng trong phần tử biểu mẫu và phản hồi cụ thể đối với sự kiện gửi và có hành vi làm mới trang mặc định

Tiếp theo, hãy xem JS. Hãy chú ý đến các nhận xét được thêm vào đoạn mã bên dưới để mô tả mã mới được thêm vào

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
2

Như chúng ta có thể thấy trong đoạn mã, chúng ta đã thêm 3 trình xử lý sự kiện riêng biệt vào sự kiện gửi biểu mẫu. Lý do tại sao việc sử dụng thuộc tính trình xử lý sự kiện

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
1 sẽ không thành công trong trường hợp này là do thuộc tính chỉ có thể được đặt thành một giá trị và bất cứ khi nào chúng tôi đặt lại giá trị, nó sẽ ghi đè lên giá trị trước đó

Vì vậy, nếu chúng tôi đã cập nhật cùng mã ở trên để sử dụng thuộc tính trình xử lý sự kiện, thì chỉ thuộc tính trình xử lý sự kiện

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
1 cuối cùng mới được đăng ký. Hãy xem nó trông như thế nào. Hãy chú ý đến các nhận xét khi bạn đọc đoạn mã sau

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3

Trong đoạn mã trên, chúng ta có thể theo dõi rằng hai trình xử lý sự kiện

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
1 đầu tiên [để lấy giá trị biểu mẫu/đặt giá trị câu chuyện và hiển thị nút đặt lại] đều đã bị ghi đè bởi trình xử lý sự kiện
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
1 cuối cùng. Bây giờ khi chúng tôi gửi biểu mẫu, trang web của chúng tôi sẽ hiển thị quảng cáo, nhưng nó sẽ không hiển thị câu chuyện hoặc nút đặt lại

Bạn có thể đang nghĩ, vậy thì sao. Chúng ta không thể kết hợp từng phản ứng đối với việc gửi biểu mẫu vào một chức năng xử lý sự kiện sao?

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
6

Có, chúng tôi có thể làm điều này và chúng tôi có thể sử dụng chú thích mã để gắn nhãn các phản ứng khác nhau mà chúng tôi đang thực hiện đối với việc gửi biểu mẫu

Chúng ta cũng có thể làm điều này bằng cách sử dụng phương thức

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3, giống như đoạn mã sau minh họa. Lưu ý rằng dấu chấm lửng
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
2 đại diện cho mã không thay đổi được bỏ qua trong ví dụ

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
9

Nếu chúng ta có thể làm điều này, nó đặt ra câu hỏi. tại sao chúng ta KHÔNG làm điều này?

Khi chúng ta nói về tổ chức mã và lựa chọn giữa việc đưa mã vào một chức năng hoặc vào nhiều chức năng [hoặc trình xử lý sự kiện], chúng ta nên tự hỏi mình, "điều gì sẽ làm cho mã của tôi dễ đọc và dễ hiểu hơn?". Sẽ có một số khác biệt khi chúng ta trả lời câu hỏi này, nhưng một hướng dẫn tốt cho việc tổ chức mã là tách mã theo chức năng của nó trong ứng dụng của chúng ta

Với chức năng mở rộng của trang web Mad Libs, chúng tôi hiện có 3 phản ứng đối với việc gửi biểu mẫu. nhận và đặt giá trị câu chuyện Mad Lib, hiển thị quảng cáo và hiển thị nút đặt lại. Theo như tổ chức mã của chúng tôi, chúng tôi có hai tùy chọn chính

  • Sắp xếp ba phản ứng thành một chức năng xử lý sự kiện gửi dựa trên mục đích chung của nó là phản hồi sự kiện gửi
  • Sắp xếp ba phản ứng thành ba chức năng trình xử lý sự kiện gửi riêng biệt dựa trên nhận thức rằng mỗi phản ứng có một mục đích khác nhau trên trang web của chúng tôi [như hiển thị quảng cáo so với hiển thị câu chuyện Mad Libs]

Vậy đâu là sự lựa chọn chính xác? . Đó là sự thật

Tuy nhiên, nếu sự kiện gửi của chúng ta kích hoạt 5 hoặc 10 phản ứng khác nhau, thì mã của chúng ta sẽ dễ hiểu hơn nếu chúng ta tách các phản ứng của mình thành nhiều trình xử lý sự kiện thay vì sử dụng một trình xử lý sự kiện rất lớn. Đây là một ví dụ về việc sử dụng nhiều trình xử lý sự kiện để cải thiện tổ chức mã và mức độ dễ đọc của nó

Hoặc, điều gì sẽ xảy ra nếu chúng tôi muốn quảng cáo chỉ hiển thị một lần và không phải mỗi khi biểu mẫu được gửi - tốt, chúng tôi cần tách quảng cáo thành trình xử lý sự kiện của riêng mình mà chúng tôi có thể hủy sau khi chạy một lần. Nếu ban đầu chúng tôi đã chọn tách từng phản ứng thành trình xử lý sự kiện riêng, thì chúng tôi có thể dễ dàng cập nhật mã của mình để đáp ứng yêu cầu mới [chỉ hiển thị quảng cáo một lần]. Đây là một ví dụ về việc sử dụng nhiều trình xử lý sự kiện để cải thiện mức độ mã của chúng tôi mở rộng khi yêu cầu thay đổi

Bởi vì việc sử dụng trình xử lý sự kiện với phương pháp

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3 cho phép chúng tôi đính kèm nhiều trình xử lý vào cùng một sự kiện, chúng được coi là lựa chọn tốt nhất cho các ứng dụng mở rộng quy mô [lớn hơn và thay đổi yêu cầu]; . Vì vậy, về sau, bạn nên chọn sử dụng trình xử lý sự kiện thay vì các thuộc tính của trình xử lý sự kiện

Bạn cũng nên tạm dừng định kỳ để tự hỏi mình "điều gì sẽ làm cho mã của tôi dễ đọc và dễ hiểu hơn?". Chúng tôi mới bắt đầu tìm hiểu về những cách mới để tổ chức mã của mình, vì vậy nếu bạn chưa cảm thấy thoải mái với quy trình ra quyết định này, điều đó hoàn toàn bình thường và được mong đợi. Ý tưởng là bắt đầu suy ngẫm về những câu hỏi này, nhưng không quá bận tâm đến việc tìm kiếm cách tổ chức mã hiệu quả nhất hoặc "hoàn hảo" nhất. Cần phải thực hành cũng như thực sự xây dựng các ứng dụng lớn hơn và phức tạp hơn để có được tổ chức mã tốt

Ngoài ra, hãy lưu ý rằng mặc dù luôn có nhiều giải pháp khi nói đến tổ chức mã [và các lợi ích cũng như nhược điểm cần xem xét cho từng giải pháp], nhưng vẫn có những phương án dự phòng hữu ích để luôn kết hợp vào mã của bạn

  • Sử dụng nhận xét mã để mô tả các chức năng khác nhau trong tập lệnh của bạn. Bạn không cần phải quá nhiệt tình, nhưng nó có thể hữu ích khi có các đoạn dài hơn hoặc khi bạn có một hàm dài thực hiện nhiều việc
  • Sử dụng tên biến và hàm mô tả
  • Sử dụng khoảng cách chính xác, dòng mới và thụt đầu dòng. Điều này giúp ích rất nhiều cho khả năng đọc

Thông tin thêm về chức năng gọi lại

Gọi lại hoặc chức năng gọi lại là một khái niệm trong lập trình máy tính mà nhiều ngôn ngữ thực hiện. Hàm gọi lại [hoặc chỉ "gọi lại"] là bất kỳ hàm nào được truyền cho một hàm hoặc phương thức khác dưới dạng đối số. Tuy nhiên, chức năng gọi lại này không được gọi ngay lập tức. Hàm/phương thức nhận hàm gọi lại làm đối số sẽ gọi ["gọi lại"] hàm sau đó

Chúng ta có thể thấy quá trình này đang hoạt động trong phương thức

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3. Hãy xem lại phương pháp này.
// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3 có hai tham số bắt buộc. Trong mã giả, điều này trông giống như

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3
  • // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    36 là đối tượng mà chúng tôi đang nhắm mục tiêu — một phần tử HTML, đối tượng
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    6 hoặc đối tượng
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    0
  • // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    39 là tham số đầu tiên. Ở đây chúng tôi sẽ chuyển vào một chuỗi có tên của sự kiện mà chúng tôi đang tạo trình nghe cho
  • // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    60 là tham số thứ hai. Ở đây chúng ta sẽ chuyển vào một hàm chứa tất cả mã mà chúng ta muốn chạy để phản ứng lại sự kiện

Mặc dù chúng ta đang chuyển một hàm gọi lại làm đối số thứ hai của phương thức

// These are the scripts from the Mad Libs project.
window.onload = function[] {
  let form = document.querySelector["form"];
  // new code below
  form.addEventListener["submit", function[event] {
    ...
    ...
    document.querySelector["div#story"].removeAttribute["class"];
    event.preventDefault[];
  // new code below  
  }]; 
};
3, nhưng hàm này chỉ được gọi khi sự kiện tương ứng xảy ra. Không phải ngay lập tức, nhưng sau đó. Sự khác biệt về thời gian này rất quan trọng và là lý do chính khiến các cuộc gọi lại tồn tại, đó là để xử lý mã JavaScript không đồng bộ. Bây giờ chúng ta sẽ không đi sâu vào vấn đề đó, nhưng chúng ta sẽ xem xét lại tính không đồng bộ và gọi lại sau trong chương trình, vì vậy sẽ có nhiều cơ hội hơn để làm quen với khái niệm này

Ngoài ra, hãy lưu ý rằng việc phân loại hàm là "gọi lại" không liên quan đến loại hàm [khai báo, biểu thức hoặc cách khác — cách chúng ta xác định hàm]. Thay vào đó, nó liên quan đến ứng dụng của một chức năng — nơi chúng tôi đang sử dụng nó trong mã của mình. Bất kỳ hàm nào được sử dụng làm đối số cho hàm khác sẽ tự động trở thành hàm gọi lại

Bạn sẽ khó có thể tạo một hàm tùy chỉnh trong chương trình lấy một hàm làm đối số. Sẽ không có nhiều trường hợp sử dụng cho điều đó. Tuy nhiên, bạn sẽ làm việc với một số phương thức và hàm dựng sẵn [của JavaScript hoặc API Web] yêu cầu hàm cho đối số [gọi lại]

Nếu điều này nghe có vẻ phức tạp và khó hiểu, thì điều đó hoàn toàn có thể xảy ra — đặc biệt nếu bạn là người mới viết mã. Có rất nhiều điều phức tạp đang diễn ra dưới mui xe. Học lái xe là một chuyện — và không quá khó. Nhưng học cách chế tạo và bảo dưỡng ô tô còn nhiều việc hơn thế. Chúng tôi sẽ thường xuyên xem lại thuật ngữ JavaScript và hoạt động bên trong của cả JS và trình duyệt web của chúng tôi, vì vậy sẽ có nhiều cơ hội hơn để xem xét và thực hành

Tóm tắt và Mã hoàn chỉnh cho Dự án Mad Libs

Trong bài học này chúng ta đã học về lắng nghe sự kiện. Một số chủ đề chính chúng tôi đề cập là

  • Lắng nghe sự kiện là một phương pháp xử lý sự kiện khác. Xử lý sự kiện là một thuật ngữ chung mô tả các quy trình và công cụ mà nhà phát triển sử dụng để viết mã đáp ứng các sự kiện
  • Lắng nghe sự kiện là quá trình tạo trình lắng nghe sự kiện trong mã của chúng tôi để lắng nghe và phản ứng với các sự kiện xảy ra trong trang web của chúng tôi
  • Khi chúng tôi gọi
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    3 trên một mục tiêu [phần tử DOM,
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    0 hoặc
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    6], quá trình này được gọi là đăng ký trình lắng nghe sự kiện
  • Chúng ta có thể tạo một trình lắng nghe sự kiện bằng phương thức
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    3, phương thức này nhận hai đối số
    • Đối số đầu tiên là tên sự kiện dưới dạng chuỗi, chẳng hạn như
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        form.onsubmit = function[event] {
          // omitted code to get the value for each form input
          ...
          // omitted code to set the story variables to the values we got from the form
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        };
      };
      
      36 hoặc
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      6
    • Đối số thứ hai là hàm xử lý, hàm xử lý phản ứng với sự kiện
  • Lợi ích của việc sử dụng trình lắng nghe sự kiện là chúng ta có thể tạo nhiều trình xử lý cho cùng một sự kiện trên cùng một mục tiêu [một phần tử DOM,
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    0,
    // These are the scripts from the Mad Libs project.
    window.onload = function[] {
      let form = document.querySelector["form"];
      // new code below
      form.addEventListener["submit", function[event] {
        ...
        ...
        document.querySelector["div#story"].removeAttribute["class"];
        event.preventDefault[];
      // new code below  
      }]; 
    };
    
    6 hoặc cách khác]. Điều này cải thiện tổ chức mã của chúng tôi và mức độ dễ đọc và dễ hiểu, đồng thời giúp mã của chúng tôi có thể mở rộng tốt. Trình xử lý sự kiện được coi là cách được đề xuất để thiết lập xử lý sự kiện trong ứng dụng
  • Bất kỳ hàm nào được truyền vào một hàm/phương thức khác làm đối số được gọi là hàm gọi lại
    • Hàm "xử lý" mà chúng ta truyền vào phương thức
      // These are the scripts from the Mad Libs project.
      window.onload = function[] {
        let form = document.querySelector["form"];
        // new code below
        form.addEventListener["submit", function[event] {
          ...
          ...
          document.querySelector["div#story"].removeAttribute["class"];
          event.preventDefault[];
        // new code below  
        }]; 
      };
      
      3 là hàm gọi lại
    • Các hàm gọi lại là tất cả về ứng dụng của các hàm — nơi chúng đang được sử dụng trong mã của chúng ta — và chúng rất quan trọng đối với JavaScript không đồng bộ, mà chúng ta sẽ tìm hiểu về sau

Để xem mã đã hoàn thành cho dự án Mad Libs của chúng tôi, hãy truy cập trang cheat. Mã này bao gồm chức năng mới của nút đặt lại và quảng cáo cũng như trình xử lý sự kiện riêng biệt cho từng phản ứng đối với sự kiện gửi biểu mẫu

Trình xử lý sự kiện trong JavaScript là gì?

Trình xử lý sự kiện là mã JavaScript gọi một đoạn mã cụ thể khi một hành động cụ thể xảy ra trên phần tử HTML . Trình xử lý sự kiện có thể gọi mã JavaScript trực tiếp hoặc một hàm.

Trình xử lý sự kiện khác với sự kiện như thế nào?

Trong lập trình, trình xử lý sự kiện là một quy trình gọi lại hoạt động không đồng bộ sau khi một sự kiện diễn ra . Nó ra lệnh cho hành động theo sau sự kiện. Lập trình viên viết mã cho hành động này diễn ra. Một sự kiện là một hành động diễn ra khi người dùng tương tác với một chương trình.

addEventListener có phải là trình xử lý sự kiện không?

Ví dụ. Phương thức addEventListener[] gắn một trình xử lý sự kiện vào phần tử đã chỉ định . Phương thức addEventListener[] gắn một trình xử lý sự kiện vào một phần tử mà không ghi đè lên các trình xử lý sự kiện hiện có. Bạn có thể thêm nhiều trình xử lý sự kiện vào một phần tử.

Lợi thế của việc triển khai trình xử lý sự kiện so với trình xử lý sự kiện là gì?

Lợi ích của việc sử dụng trình lắng nghe sự kiện là chúng ta có thể tạo nhiều trình xử lý cho cùng một sự kiện trên cùng một mục tiêu [phần tử HTML, cửa sổ, .

Chủ Đề