「knockout.jsでデータの検索ができるようにする」を別ウィンドウで開く
各種サンプルとソース一覧
|
PCスキルの小技・忘却防止メモ
|
knockout.jsでデータの検索ができるようにする
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>knockout.jsでデータの検索ができるようにする</title>
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="knockout-2.1.0beta.js"></script>
<script type="text/javascript">
$(document).ready(function () {
ko.applyBindings(new ViewModel());
});
function ViewModel() {
var self = this;
self.jsonTemporary = {};
self.jsonData = ko.observable();
self.search = ko.observable();
self.loading = ko.observable(true);
self.result = ko.observable();
// 表示
self.GotoView = function(json) {
if (json["item"].length != 0)
{
this.jsonData(json.item);
}
else
{
this.jsonData("");
}
this.loading(false);
};
// 検索ボタンが押されたとき
self.RunSearch = function(e) {
e.loading(true);
e.result();
if (e.search() == "" || e.search() == undefined)
{
// 何も入力されていない
self.GotoView(e.jsonTemporary);
}
else
{
jsonSearch = getJsonOfSearchWord(e.jsonTemporary, e.search());
self.GotoView(jsonSearch);
if (jsonSearch["item"].length != 0)
{
e.result("「" + e.search() + "」を含む結果");
}
else
{
e.result("「" + e.search() + "」を含む結果がありません(「味」が検索対象)");
}
}
};
// デフォルトでの表示:元データを読込んでおく
$.getJSON("./testdata/testdataC.txt", {}, function(json){
self.jsonTemporary = json; // 何回も読込みされるのがイヤなので保管しておく
self.GotoView(self.jsonTemporary);
}
);
}
// 検索ワードを含むデータだけ返す
function getJsonOfSearchWord(ary, search)
{
returnAry = {"item":[]};
for (var i in ary["item"])
{
if (ary["item"][i]["taste"].match(search) != null)
{
returnAry["item"].push(ary["item"][i]);
}
}
return returnAry;
}
</script>
<style type="text/css">
table{margin-top:0.5em;}
th, td{
border:1px solid #ccc;
}
td
{
padding:8px;
}
</style>
</head>
<body>
<h1>knockout.jsでデータの検索ができるようにする</h1>
<div class="wrap">
味を検索:<input type="text" data-bind="value: search" /><button data-bind="click: RunSearch">検索</button><br />
<small>※検索の対象は「味」だけにしています</small><br />
<div data-bind="visible: loading()" style="padding:15px 10px;">
<!-- 「http://www.ajaxload.info/」で画像作成。 -->
<img src="images/ajax-loader.gif" /><br />
</div>
<h2 data-bind="visible: result, text: result"></h2>
<table data-bind="visible: jsonData()">
<thead><tr><th>品名</th><th>金額</th><th>味</th></thead>
<tbody data-bind="foreach: jsonData">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: price"></td>
<td data-bind="text: taste"></td>
</tr>
</tbody>
</table>
</div>
<div style="font-size:10pt;text-align:right;margin-top:0.5em;">
<a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
<a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
</div>
<div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
Copyright © 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
</div>
</body>
</html>