Khi tạo ứng dụng JS phức tạp, ưu điểm và nhược điểm của việc sử dụng đối tượng quan sát toàn cầu kích hoạt sự kiện là gì và tất cả các đối tượng khác đăng ký so với trộn lẫn hoặc tạo mẫu phương pháp pub/sub trên tất cả các đối tượng có trách nhiệm kích hoạt sự kiện của riêng họ?Ưu điểm/nhược điểm của đối tượng quan sát toàn cầu so với mixin
Đưa ví dụ như một trò chơi thẻ trong đó có đại lý, các đối tượng người chơi, và bảng (psuedocode-ish sau):
// "Global" observer version
var observer = {
// publish and subscribe methods defined here
};
dealer.deal = function(cards) {
// performs logic for dealing cards
observer.publish('dealer:dealt', cards, this);
};
player.play = function(cards) {
// performs logic for which card is played
observer.publish('player:played', cards, this);
};
table.showCards = function(cards, player) {
// performs logic for showing cards that the dealer dealt
// or that the player played
};
observer.subscribe('dealer:dealt', table.showCards);
observer.subscribe('player:played', table.showCards);
vs
// Pub/sub mixin/prototype version
dealer.deal = function(cards) {
// performs logic for dealing cards
this.publish('dealt', cards);
};
player.play = function(cards) {
// performs logic for which card is played
this.publish('played', cards);
};
table.showCards = function(cards) {
// performs logic for showing cards that the dealer dealt
// or that the player played
};
dealer.subscribe('dealt', table.showCards);
player.subscribe('played', table.showCards);
Bạn đã kết thúc bằng cách nào? Tôi hiện đang vật lộn với cùng một quyết định. Và thậm chí một năm sau khi bạn đặt câu hỏi, dường như không có dữ liệu rõ ràng để giúp bạn lựa chọn. Các hồ bơi thậm chí toàn cầu dường như giải phóng nhiều hơn và ít tốn kém bộ nhớ hơn, nhưng khi các hệ thống bắt đầu trở nên thực sự lớn, tôi tự hỏi liệu nó có trở nên phức tạp hơn không. – nicholas