一、基础部分lastName
单次绑定
从ViewModel绑定至UI这一层只进行一次绑定,不追踪数据在任何一方的
function AppViewModel() { this.firstName = "Bert"; this.lastName = "Bertington";} ko.applyBindings(new AppViewModel()); <p>First name:<stong data-bind="text:firstName"></strong></p> <p>Last name:<stong data-bind="text:lastName"></strong></p>
双向绑定
输入框中值发生改变时,标签中显示内容相应发生改变
function AppViewModel() { this.firstName = ko.observable("Bert"); this.lastName = ko.observable("Bertington"); } ko.applyBindings(new AppViewModel()); <p>First name:<strong data-bind="text: firstName"></strong></p> <p>Last name:<strong data-bind="text: lastName"></strong></p> <p>First name:<input date-bind="value: firstName"></p> <p>Last name: <input date-bind="value: lastName"></p>
依赖绑定
fullName依赖于firstName和lastName,改变firstName和lastName任意值,fullName的显示也相应改变
function AppViewModel() { this.firstName = ko.observable("Bert"); this.lastName = ko.observable("Bertington"); this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this); } ko.applyBindings(new AppViewModel()); <p>First name:<strong data-bind="text: firstName"></strong></p> <p>Last name:<strong data-bind="text: lastName"></strong></p> <p>First name:<input data-bind="value: firstName"></p> <p>Last name:<input data-bind="value:lastName"></p> <p>Full name: <strong data-bind="text: fullName"><strong></p>
绑定数组
seats对象绑定了一个集合对象,在html view中,通过foreach指令渲染视图
<h2>Your seat reservations</h2> <table> <thead> <tr> <th>Passenger name</th> <th>MealSurcharge</th> <th>Surcharge</th> </tr> </thead> <tbody> <tr> <td data-bond="text: name"></td> <td data-bind="meal().mealNmae"></td> <td data-bind="text:meal().price"></td> </tr> </tbody> </table> function SeatReservation(name, initialMeal) { var self = this; self.name = name; self.meal = ko.observable(initialMeal); } function ReservationsViewModel() { var self = this; self.availableMeals = [ { mealName: "Standard (sandwich)", price: 0 }, { mealName: "Premium (lobster)", price: 34.95 }, { mealName: "Ultimate (whole zebra)", price: 290 } ]; self.seats = ko.observableArray([ new SeatReservation("Steve", self.availableMeals[1]), new SeatReservation("Bert", self.availableMeals[2]) ]); } ko.applyBindings(new ReservationsViewModel());
哪位大神这玩意怎么编写代码 我能说这是一个一个敲出来的吗? 实在是累啊 求好心人告知
网友评论