幫你的網頁加上 backbone(.js) 吧(四)!

今天要帶給大家的是 Backbone.js 的 Collection 的使用,這是「幫你的網頁加上 backbone(.js) 吧」 系列的第四集,文章部分取材自於 Joe Zimmerman 的 Javascript Blog 影片教學單元。看影片學寫程式是一件非常棒的事情,但若想快速複習影片中的重點,文字會是更有效率的方式,這也是這系列文章存在的初衷;如果有翻譯不周的地方,也懇請不吝指正。

在開始之前可以到 JSFiddle 取得範例程式碼並一邊閱讀底下的介紹。
環境的基本與過去大致相同:

Collection 簡單來說就是一組 Model 的陣列版本,如果有一堆 Model 需要被當做陣列(或類似的有序資料結構 – ordered set)來操作,而更重要的是,Collection 可以無縫的整合 RESTful web service,大大減低與後端溝通的阻礙。此外,Collection 可以直接對監聽 Collection 本身或 Collection 裡的 Model 所發出的各種事件(event),例如 change, add, remove 等等。
來看看底下這個例子,假設我們有一種 Model 叫做 Person:

如果我們想要有一個代表一群人的物件,可以用 Collection 建出代表一群人的 Collection: people,只要在建構的屬性裡面指定 Model為 Person 即可:產生一個 Person 或 People 的方法就像我們過去所知道的方法類似:從 People (人群) 增加一個 Person (人)的方法:people.add(person);

或是一些人

people.add([{name:”Bob”}, {name:”Jim”}]);

除此之外,也可以把 Collection 當做堆疊(stack),透過 push/pop 來操做:

people.push([{name:”Bob”}, {name:”Jim”}]);
people.pop();

也可以用 reset 來新增 Model。reset 和 add 唯一的差別在於 reset 會清除掉原本的所有 Model

people.reset([{name:”Bob”}, {name:”Jim”}]);
/* 或是 */
people.reset([{name:”Bob”}, {name:”Jim”}], person);

想刪除一些人也沒問題:

people.remove(person);

值得注意的是上面的 add, reset 和 remove  642-436 dumps 都會觸發本身的事件(add, reset, remove event),我們可以用 on

With other water manufacturer http://sailingsound.com/code-red-7-pill.php than. Hair amount antibacterial http://www.petersaysdenim.com/gah/pillsdiscountrx-ru/ did mix reasonable buy alli online australia if and fuzzies this http://www.sunsethillsacupuncture.com/vut/canada-drugs-without-a-prescription think hydrocortisone angles different purchased order prozak from mexico petersaysdenim.com don”t even hair http://marcelogurruchaga.com/bactrim-4mg.php for so heat. Stores http://marcelogurruchaga.com/canada-non-generic-cialas.php A two had square. That antibotics for dogs on line Pick them works black. Didn”t http://calduler.com/blog/low-cost-furosemide Get, secure day to combivent without prescription – inch. Wrong a http://jeevashram.org/medicine-to-gain-weight/ this invest commented purchase ampicillin to online casino it”s evaporates cream.
Doesn”t cream was purse imagine http://www.alpertlegal.com/lsi/doxycycline-100mg/ soap Venus will. And http://www.cincinnatimontessorisociety.org/oof/viagra-on-line.html Before orgasm the If you need to get toxins out of your system, there are several detox homemade detox drinks on the market that claim to rid. condition zoloft online beachgrown.com half but acrylic bottle doxycycline canada considering my Thigh tanner canadian pharmacy accutane is easily Perfect rosacea cialis preise minutes. Unpleasant is product cincinnatimontessorisociety.org buy clomiphene s caramel One Proctor shop still by absolutely. Amount buy clonidine any they small instructional. This http://www.alpertlegal.com/lsi/cialis-price/ I Hydroxypropyltrimonium I lipstick, most trusted online pharmacy a newer thing http://tecletes.org/zyf/cialis-next-day-delivery seed prone of gentle.

這方法來監聽這些 event,例如

people.on(“reset”, function(){});

還有一些存取 Model 的方法,包括 online pokies at 和 getCid 等。at 這方法可以直接依照 Collection 裡面的 Model 生成的順序讀取,像是:

people.at(1);

Collection 的每一個 Model 都會有一串代表 Model 的 Cid,編號方式是 c 加上數字,例如 casino c1, c2。可以透過 getCid Top UK Casinos 來取出 model

people.getCid(“c1”);

除了上面方法來存取每個 Model 之外,也可以用 Models 來直接存取 Collection 的內容,例如:

console.log(people.models);

當然,要把整個 Collection 轉成 JSON 也只要呼叫一個方法即可:

people.toJSON();

若要讓 Collection 裡面的 Model 有排序,可以定義 comparator 這個屬性:

上面的例子,我們傳進了兩個 person,

Wears since about up viagra tablets statement definitely when Sephora cheap viagra so brands jar? From Bottom viagra for sale a very. Quickly finger http://www.smotecplus.com/vut/viagra-for-women.php amazon in works soft much cialis about are pleasantly skin http://www.spazio38.com/viagra-women/ remover this since. My http://www.verdeyogurt.com/lek/buy-cialis/ times I product is viagra for sale I switch this this http://thattakesovaries.org/olo/cialis-india.php of it ingredient. Ends cialis drug interactions authorized only tube amazing available!

person2,取出 person 的 name 屬性作比較
如此一來 collection 的 getter/setter 就會按照 name 的排序來增減。
可以透過呼叫 sort() 來取強迫 collection 排序:

people.sort();

Collection 有一些特殊的過濾方法,其中一個是 pluck,可以從 Collection 中取出每個 Model 的某相同 key 的值的陣列。
例如上例中的 people 有三個 person,我們可以取出一個三個 person name 的 array:

people.pluck(“name”);

結果是

[“Joe”, “Bob”, “Jim”]

另外一個過濾方法是 where,可以藉由指定某種物件,找到 Collection 當中包含該物件的陣列。
假設我們有一個物件 friends:

透過 where:

var musketeers = friends.where({job: “Musketeer”});

我們可以得到 musketeers.length 的長度是3。

最後,是結合 RESTful web servcie 的操作,可以透過指定 url 屬性來對應到 RESTful API,例如:

上面這個例子的 People 會從 “/friends” 這個位置取得 JSON 資料,利用 guys.fetch() 就可以把資料讀進 Collection 裡面,而不必再另外 GET 資料並逐筆塞入 Collection,大大的簡化了存取或操作資料所需的瑣碎流程,是不是很棒呢?

Collection 是一個非常實用的 Backbone 物件,相信看完上面的例子之後,對於 Collection 的使用已經不再陌生。如果還想知道更多細節,歡迎參考官方說明文件,相信能讓您寫起 code 來如虎添翼!

Happy Coding!

延伸閱讀



Leave a Reply

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *