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用于绑定被选中的座位类型。