Skip to Content
JAVASCRIPT網頁應用程式設計
book

JAVASCRIPT網頁應用程式設計

by Alex MacCaw
January 2013
Intermediate to advanced
332 pages
5h 23m
Chinese
GoTop Information, Inc.
Content preview from JAVASCRIPT網頁應用程式設計
66
|
第四章
}
});
// 建立控制器物件實體,呼叫控制器的 init() 函式
new ToggleView("#view");
});
這段範例程式還有做另一項調整:這次我們不直接將檢視器元件寫死在控制器裡面,改
成是在建立控制器的物件實體時,動態傳入檢視器元件。這是項重大的改進,因為這麼
一來,我們所開發的控制器就能被許多不同的元件重複使用,讓重複程式碼的數量降到
最低。
存取檢視器
有一種常見的做法,是讓每個檢視器都分別對應到一個專屬的控制器。由於每個檢視器
都會設定專屬的 ID 屬性值,因此可輕易的將它傳入控制器裡使用。不過包在檢視器裡
面的網頁元件,要透過 class 屬性值來區分,而非 ID 屬性值,這樣不同檢視器裡的網頁
元件,才不會發生衝突的狀況。一般我們會利用這種做法優化程式架構,不過倒也不會
嚴格的要求所有程式設計師,一定都得遵循這樣的做法。
本章目前為止的範例程式,都是利用
jQuery()
選取項來存取檢視器,然後在控制器裡儲
存一組檢視器的區域參照值。之後如果想要搜尋檢視器裡的網頁元件,可以透過這組檢
視器的參照值,加快搜尋速度:
// ...
init: function(view){
this.view = $(view);
this.form = this.view.find("form");
}
不過如果在控制器裡面寫一堆選取項,會讓控制器需要一直不停的搜尋 DOM 元件。選
取項和變數名稱的對應關係,可以集中定義在一處,讓控制器的程式看起來更一目瞭
然,舉例如下:
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 第3版 ―ES2015以降の最新ウェブ開発

初めてのJavaScript 第3版 ―ES2015以降の最新ウェブ開発

Ethan Brown, 武舎 広幸, 武舎 るみ
PHP编程:第4版

PHP编程:第4版

Kevin Tatroe, Peter MacIntyre
Strange Code

Strange Code

Ronald T. Kneusel
Perfecting Your Thinking Skills

Perfecting Your Thinking Skills

MIT Sloan Management Review

Publisher Resources

ISBN: 9789862766811