Knockout JS 演示样例
五个小样例,来自Knockout JS官方站点。
//tutorial 1
//following codes uses to demonstrate observable values and target bound ways especially method bound <!-- This is a *view* - HTML markup that defines the appearance of your UI --> <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> <button data-bind="click: capitalizeLastName">Go caps</button> // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington"); this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this); this.capitalizeLastName = function() {
var currentVal = this.lastName(); // Read the current value
this.lastName(currentVal.toUpperCase()); // Write back a modified value
};
} // Activates knockout.js
ko.applyBindings(new AppViewModel()); //tutorial 2
//this demo shows how to use observable array to bind html elements and how to define model <h2>Your seat reservations (<span data-bind="text: seats().length"></span>)</h2> <table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr></thead>
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name" /></td>
<td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td data-bind="text: formattedPrice"></td>
<td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
</tr>
</tbody>
</table> <button data-bind="click: addSeat, enable: seats().length < 5">Reserve another seat</button> <h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3> // Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal); self.formattedPrice = ko.computed(function() {
var price = self.meal().price;
return price ? "$" + price.toFixed(2) : "None";
});
} // Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
var self = this; // Non-editable catalog data - would come from the server
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
]; // Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[0])
]); // Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.seats().length; i++)
total += self.seats()[i].meal().price;
return total;
}); // Operations
self.addSeat = function() {
self.seats.push(new SeatReservation("", self.availableMeals[0]));
}
self.removeSeat = function(seat) { self.seats.remove(seat) }
} ko.applyBindings(new ReservationsViewModel()); //tutorial 3
//this demo shows how to use ajax to get data and update observable arrary <script src="/scripts/lib/sammy.js" type="text/javascript"></script> <!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
<li data-bind="text: $data,
css: { selected: $data == $root.chosenFolderId() },
click: $root.goToFolder"></li>
</ul> <!-- Mails grid -->
<table class="mails" data-bind="with: chosenFolderData">
<thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
<tbody data-bind="foreach: mails">
<tr data-bind="click: $root.goToMail">
<td data-bind="text: from"></td>
<td data-bind="text: to"></td>
<td data-bind="text: subject"></td>
<td data-bind="text: date"></td>
</tr>
</tbody>
</table> <!-- Chosen mail -->
<div class="viewMail" data-bind="with: chosenMailData">
<div class="mailInfo">
<h1 data-bind="text: subject"></h1>
<p><label>From</label>: <span data-bind="text: from"></span></p>
<p><label>To</label>: <span data-bind="text: to"></span></p>
<p><label>Date</label>: <span data-bind="text: date"></span></p>
</div>
<p class="message" data-bind="html: messageContent" />
</div> function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
self.chosenFolderData = ko.observable();
self.chosenMailData = ko.observable(); // Behaviours
self.goToFolder = function(folder) { location.hash = folder };
self.goToMail = function(mail) { location.hash = mail.folder + '/' + mail.id }; // Client-side routes
Sammy(function() {
this.get('#:folder', function() {
self.chosenFolderId(this.params.folder);
self.chosenMailData(null);
$.get("/mail", { folder: this.params.folder }, self.chosenFolderData);
}); this.get('#:folder/:mailId', function() {
self.chosenFolderId(this.params.folder);
self.chosenFolderData(null);
$.get("/mail", { mailId: this.params.mailId }, self.chosenMailData);
}); this.get('', function() { this.app.runRoute('get', '#Inbox') });
}).run();
}; ko.applyBindings(new WebmailViewModel()); //tutorial 4
// shows how to define custom binding target <h3 data-bind="text: question"></h3>
<p>Please distribute <b data-bind="text: pointsBudget"></b> points between the following options.</p> <table>
<thead><tr><th>Option</th><th>Importance</th></tr></thead>
<tbody data-bind="foreach: answers">
<tr>
<td data-bind="text: answerText"></td>
<td data-bind="starRating: points"></td>
</tr>
</tbody>
</table> <h3 data-bind="fadeVisible: pointsUsed() > pointsBudget">You've used too many points! Please remove some.</h3>
<p>You've got <b data-bind="text: pointsBudget - pointsUsed()"></b> points left to use.</p>
<button data-bind="jqButton: { enable: pointsUsed() <= pointsBudget }, click: save">Finished</button> // ----------------------------------------------------------------------------
// Reusable bindings - ideally kept in a separate file ko.bindingHandlers.fadeVisible = {
init: function(element, valueAccessor) {
// Start visible/invisible according to initial value
var shouldDisplay = valueAccessor();
$(element).toggle(shouldDisplay);
},
update: function(element, valueAccessor) {
// On update, fade in/out
var shouldDisplay = valueAccessor();
shouldDisplay ? $(element).fadeIn() : $(element).fadeOut();
}
}; ko.bindingHandlers.jqButton = {
init: function(element) {
$(element).button(); // Turns the element into a jQuery UI button
},
update: function(element, valueAccessor) {
var currentValue = valueAccessor();
// Here we just update the "disabled" state, but you could update other properties too
$(element).button("option", "disabled", currentValue.enable === false);
}
}; ko.bindingHandlers.starRating = {
init: function(element, valueAccessor) {
$(element).addClass("starRating");
for (var i = 0; i < 5; i++)
$("<span>").appendTo(element); // Handle mouse events on the stars
$("span", element).each(function(index) {
$(this).hover(
function() { $(this).prevAll().add(this).addClass("hoverChosen") },
function() { $(this).prevAll().add(this).removeClass("hoverChosen") }
).click(function() {
var observable = valueAccessor(); // Get the associated observable
observable(index+1); // Write the new rating to it
});
});
},
update: function(element, valueAccessor) {
// Give the first x stars the "chosen" class, where x <= rating
var observable = valueAccessor();
$("span", element).each(function(index) {
$(this).toggleClass("chosen", index < observable());
});
}
}; // ----------------------------------------------------------------------------
// Page viewmodel function Answer(text) { this.answerText = text; this.points = ko.observable(1); } function SurveyViewModel(question, pointsBudget, answers) {
this.question = question;
this.pointsBudget = pointsBudget;
this.answers = $.map(answers, function(text) { return new Answer(text) });
this.save = function() { alert('To do') }; this.pointsUsed = ko.computed(function() {
var total = 0;
for (var i = 0; i < this.answers.length; i++)
total += this.answers[i].points();
return total;
}, this);
} ko.applyBindings(new SurveyViewModel("Which factors affect your technology choices?", 10, [
"Functionality, compatibility, pricing - all that boring stuff",
"How often it is mentioned on Hacker News",
"Number of gradients/dropshadows on project homepage",
"Totally believable testimonials on project homepage"
])); //tutorial 5
//shows how to communicate with server side and how to delete items using deleted flag <h3>Tasks</h3> <form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done? " />
<button type="submit">Add</button>
</form> <ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
<a href="#" data-bind="click: $parent.removeTask">Delete</a>
</li>
</ul> You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span> <button data-bind="click: save">Save</button> function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
} function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
}); // Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
$.ajax("/tasks", {
data: ko.toJSON({ tasks: self.tasks }),
type: "post", contentType: "application/json",
success: function(result) { alert(result) }
});
}; // Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("/tasks", function(allData) {
var mappedTasks = $.map(allData, function(item) { return new Task(item) });
self.tasks(mappedTasks);
});
} ko.applyBindings(new TaskListViewModel());
Knockout JS 演示样例的更多相关文章
- 移动端报表JS开发演示样例
近期对移动端的报表开发颇有研究,细磨精算了好久,尽管到如今还是"囊中羞涩",但决定还是先抛砖引玉,拿点小干货出来和大家分享. 研究的工具是比較有代表性的FineReport. 1. ...
- SNF快速开发平台MVC-各种级联绑定方式,演示样例程序(包含表单和表格控件)
做了这么多项目,经常会使用到级联.联动的情况. 如:省.市.县.区.一级分类.二级分类.三级分类.仓库.货位. 方式:有表单需要做级联的,还是表格行上需要做级联操作的. 实现:实现方法也有很多种方式. ...
- Thrift的安装和简单演示样例
本文仅仅是简单的解说Thrift开源框架的安装和简单使用演示样例.对于具体的解说,后面在进行阐述. Thrift简述 ...
- WebGL自学教程——WebGL演示样例:開始
最终開始WebGL的演示样例了,...... 開始 使用WebGL的步骤,非常easy: 1. 获得WebGL的渲染环境(也叫渲染上下文). 2. 发挥你的想象力,利用<WebGL參考手冊> ...
- 通过Canvas及File API缩放并上传图片完整演示样例
创建一个只管的用户界面,并同意你控制图片的大小.上传到server端的数据,并不须要处理enctype为 multi-part/form-data 的情况.只一个简单的POST表单处理程序就能够了. ...
- 01_MUI之Boilerplate中:HTML5演示样例,动态组件,自己定义字体演示样例,自己定义字体演示样例,图标字体演示样例
1安装HBuilder5.0.0,安装后的界面截图例如以下: 2 依照https://www.muicss.com/docs/v1/css-js/boilerplate-html中的说明,创建上 ...
- Grunt经常使用插件及演示样例说明
下述给出了经常使用Grunt插件,并列举了部分插件演示样例: 插件名称 说明 Github地址 grunt-contrib-clean 清空文件和目录 https://github.com/grunt ...
- 跨域JSONP原理及调用详细演示样例
上篇博客介绍了同源策略和跨域訪问概念,当中提到跨域经常使用的基本方式:JSONP和CORS. 那这篇博客就介绍JSONP方式. JSONP原理 在同源策略下,在某个server下的页面 ...
- 『HTML5梦幻之旅』 - 仿Qt演示样例Drag and Drop Robot(换装机器人)
起源 在Qt的演示样例中看到了一个有趣的demo.截图例如以下: 这个demo的名字叫Drag and Drop Robot,简单概括而言,在这个demo中,能够把机器人四周的颜色拖动到机器人的各个部 ...
随机推荐
- 在MYSQL中插入当前时间,就象SQLSERVER的GETDATE()一样,以及对mysql中的时间日期操作。
在看sql教程的时候,我学的是mysql,但是教程上面的一点在mysql里面是不支持的,所以就找了其他的替代的办法 sql教程上面是这样的: 通过使用类似 GETDATE() 这样的函数,DEFAUL ...
- Scrum生命周期
Recently while cleaning up my photo albums I found some interesting old pictures which were captured ...
- [UOJ300]吉夫特
直接上lucas定理,可以得到$\binom nm=1$等价于$m$是$n$的子集(二进制) 因为数字两两不同,所以设$f_i$表示以$i$开头的满足要求的序列有多少个,转移就是$f_i\gets f ...
- 软件配置篇-java下载及安装
1.进入java官网下载合适版本: 下载地址:https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.htm ...
- 使用FluentValidation来进行数据有效性验证
之前我介绍过了使用系统自带的Data Annotations来进行数据有效性验证,今天在CodePlex上逛的时候,发现了一个非常简洁好用的库:FluentValidation 由于非常简洁,就直接拿 ...
- delphi报警声音 Beep、MessageBeep 和 Windows.Beep
转自:http://blog.csdn.net/yunqian09/article/details/5554527 我的办法,增加一个timer 设置间隔100ms,通过timer的使能否,控制报 ...
- 使用Jenkins部署Spring Boot
原文:http://www.cnblogs.com/ityouknow/p/7899349.html jenkins是devops神器,本篇文章介绍如何安装和使用jenkins部署Spring Boo ...
- 【sql】mysql数据库做两条数据替换的操作,不使用第三方变量
需求: 1.将数据库中两条数据中的唯一约束列 做值的替换 原始思想: 将两条数据查出来,在程序中设置第三方变量,进行两条数据的替换,然后将原始两条数据删除,将新的两条替换后的数据插入. 新思想: 1 ...
- 【java】处理时间字段 在数据库查询的时候只想要年月日,不想要时分秒 ,java中设置时间类型为年月日,java中设置Date中的时分秒为00.00.000
JDK8 中最简单的处理方式: @Test public void dateTest(){ Date now = new Date(); System.out.println(now); // jav ...
- 【js】判断浏览器是否IE浏览器
搜罗各种方法来判断浏览器是否为IE浏览器 1.最简单的[来自:http://www.cnblogs.com/heganlin/p/5889743.html] if(!+[1,]){ layer.msg ...