最近Knockout.jsを学習しだしたのですが、スクリプトを書いてローカルブラウザで挙動を確認するためのテンプレートを用意したのでアップします。
下記の index.html
(名前はなんでもいいけど) をローカルPCに保存して、お使いのブラウザへドラッグすれば動きます。
(外部サイトのJavaScriptライブラリを直接参照してるので、ネットに繋がってる必要はあります。)
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//ViewModel
function TestViewModel(){
self = this;
self.sample = "こんにちは世界!";
}
ko.applyBindings(new TestViewModel());
});
</script>
</head>
<body>
<span data-bind="text:sample"></span>
</body>
</html>
※JQueryは $(function() {
のところで必要です。本来はHTMLファイルの最後に ko.applyBindings()
を書かないといけないのですが、$(function() {
はページのロード後に実行されるので、ここに ko.applyBindings()
を書けばすっきりとHTMLの head エリアにスクリプトを書けるようになります。
おまけ:初心者の学習の参考になるサイト
http://learn.knockoutjs.com/
http://kojs.sukobuto.com
http://www.aoharu-b.com/cgi/sk/2012/10/javascriptknockoutjs.html