Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
設計模式
   
177
最後一件事是建立和關閉遊戲:
觀察者模式(Observer
Observer 模式廣泛的用在客戶端的 JavaScript 程式開發。所有的瀏覽器事件,包括
mouseoverkeypress 等等都是這種模式的實例。這種模式也稱為自訂事件custom
events),指的是你用程式所建立,而非瀏覽器所觸發的事件。此模式還有另一個名稱叫
訂閱者/出版者subscriber/publisher)模式。
此模式背後的 主要動機,是 促使降低耦合性 。物件不再是 去呼叫其他物件 的方法,
取而代之的是,物件可以訂閱(subscribes)其他物件的特定活動,並在發生時得到
通知。訂閱者也被稱為 observer(觀察者),被觀察的物件稱為出版者(publisher
或是主題(subject)。當有重要的事件發生時,出版者會通知(呼叫)所有的訂閱者
subscribers),且通常會用 event 物件的形式傳遞一份訊息。
範例 #1: 訂閱雜誌
讓我們來看一個具體的例子,以了解這個模式。假設你有一個出版社物件
paper
,其每日
發行報紙,還出版一份月刊雜誌。有個訂閱者
joe
會在每次出版的時候收到通知。
這個
paper
物件需要一個
subscribers
屬性,它是一個陣列,儲存著所有的訂閱者。訂閱
的動作其實就只是將訂閱者加入到這個陣列。當事件發生時,
paper
會逐一尋訪訂閱者清
單並通知他們。所謂通知,就是呼叫訂閱者物件的某個方法,因此訂閱者必須提供一 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190