サンプル
共通部分:外部JavaScript
js/ChangeValuesTracker.jsfunction ChangeTracker(root, isInitiallyDirty) { var result = function() {} var _initialState = ko.observable(ko.toJSON(root)); var _isInitiallyDirty = ko.observable(isInitiallyDirty); result.isDirty = ko.dependentObservable(function() { return _isInitiallyDirty() || _initialState() !== ko.toJSON(root); }); result.reset = function() { _initialState(ko.toJSON(root)); _isInitiallyDirty(false); }; return result; }; function setViewModel(viewModel) { viewModel.tracker = new ChangeTracker(viewModel, false); viewModel.close = function() { if (viewModel.tracker.isDirty() && !window.confirm('本当にいいんですね?(閉じる代わりにYahooに移動)')) { // キャンセル return; } else { location.href = "http://www.yahoo.co.jp/"; } } viewModel.save = function() { viewModel.tracker.reset(); } ko.applyBindings(viewModel); }
使用者:HTML
<!DOCTYPE html> <head> <meta charset="UTF-8"> <script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js'> <script type='text/javascript' src='./js/ChangeValuesTracker.js'></script> <style type="text/css"> .odd { background-color: #ccc } .even { background-color: #aaa; } </style> </head> <body> <table> <thead> <tr> <th>Delete?</th> <th>ID</th> <th>Name</th> </tr> </thead> <tbody data-bind="foreach: people"> <tr data-bind="css: { even: $index() % 2 == 0, odd: $index() % 2 != 0 }"> <td><input type="checkbox" data-bind="checked: isDeleted, attr: { name: 'isDeleted' + $index() }" /></td> <td><input type="text" data-bind="value: id, attr: { name: 'id' + $index() }" /></td> <td><input type="text" data-bind="value: name, attr: { name: 'name' + $index() }" /></td> </tr> </tbody> </table> <button data-bind="click: close">close</button> <button data-bind="click: save">save</button> <script type="text/javascript"> function Person(isDeleted, id, name) { this.isDeleted = ko.observable(isDeleted); this.id = ko.observable(id); this.name = ko.observable(name); } function ViewModel(people) { this.people = ko.observableArray(people); } var viewModels = new ViewModel([ new Person(true, 1, "Mike"), new Person(false, 2, "Tom"), new Person(true, 3, "Smith"), new Person(false, 4, "Kevin"), new Person(false, 5, "Ken"), new Person(true, 6, "Amy"), ]); setViewModel(viewModels); </script> </body> </html>