avalon對交互非常復雜的WEB應用具有天然的優勢,它擁有兩大神器:計算屬性(這相當於后端WPF的DependencyProperty)與$watch回調。 我們的訂餐系統的要求如下,它有一個總額統計,會在用戶添加刪除座位時重新計算它,並且與我們火車的座位一樣,是分不同的檔次,軟卧肯定比軟座貴,軟座比硬座貴。我們需要使用一個數組來儲存所有的座位,循環它們使用ms-each,而座位類型與價格成一一對照關系,這種結構使用哈希最合適,在JS中它的對象就是自帶的哈希,循環它們使用ms-with。如何監聽它們變動呢?座位數的變動我們可以監聽它的長度,從而調用對應的回調。而選擇座位類型時,我們一般使用下拉框,這時綁定一個ms-change事件,就搞定。
function SeatReservation(name, type) { this.name = name; this.type = type } var model = avalon.define('seatsVM', function(vm) { vm.seats = [ new SeatReservation("Steve", "硬座"), new SeatReservation("Bert", "軟卧") ]; vm.types = { "硬座": 20, "軟座": 39.99, "軟卧": 120 } vm.totalSurcharge = 0 vm.addSeat = function() { vm.seats.push(new SeatReservation("newName", "硬座")); } vm.changePrice = getPrice }) function getPrice() { var result = 0; for (var i = 0, el; el = model.seats[i++];) { result += model.types[el.type] } model.totalSurcharge = result.toFixed(2) } getPrice()//先求出已有座位的總票價 //監聽增刪 model.seats.$watch("length", getPrice)
上述代碼中定義了一個微型類,它表示預票,上面有着座位的持有人與座位類型。統計總票價有getPrice方法處理,它有幾個消費者,ms-change與$watch回調。ms-change位於視圖的下拉框中,$watch回調是用於監聽車票的數量變化。像總票價totalSurcharge 與 座位類型等重要消息都做成VM的一個屬性,方便在視圖中顯示。
<div ms-controller="seatsVM"> <div class="page-header"> <h1> seatVM </h1> </div> <div class="info"> <h3 class="seats">座位預約(<span>{{seats.size()}}</span>)</h3> <div class="money-wrap"> <h3 class="money" ms-visible="totalSurcharge > 0"> 總計費用:$ {{totalSurcharge}} </h3> </div> <div class="btns-wrap"> <button class="btn btn-primary" ms-click="addSeat" ms-enabled="seats.size() < 5">新增訂位</button> </div> </div> <table class="table"> <thead> <tr> <th>姓名</th><th>檔次</th><th>費用</th><th>操作</th> </tr> </thead> <tbody ms-each-seat="seats"> <tr> <td><input type="text" ms-duplex="seat.name" /></td> <td> <select ms-with="types" ms-duplex="seat.type" ms-mouseleave="changePrice"> <option ms-value="$key" >{{$key}}</option> </select> </td> <td>{{console.log(seat.type),types[seat.type]}}</td> <td><a href="javascript:void(0);" ms-click="$remove">刪除</a></td> </tr> </tbody> </table> </div>
在社圖中我們還試驗了許多鍾綁定,如ms-enabled,每人限購五張票,ms-visible,沒有買就不用顯示價錢,ms-duplex用於綁定被選中的座位類型。