本範例使用 Knockout 的 observableArray 與 data-bind,搭配 Bootstrap 樣式,建立可新增、修改、刪除的產品列表。適合理解 MVVM 模式如何與 DOM 互動。
<script src="knockout.js"></script> <link href="bootstrap.css" rel="stylesheet">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>產品名稱</th>
<th>原價</th>
<th>促銷價</th>
<th>操作</th>
</tr>
</thead>
<tbody data-bind="foreach: products">
<tr>
<td><span data-bind="text: $data.Id"></span></td>
<td><input type="text" data-bind="value: $data.Name" /></td>
<td><input type="text" data-bind="value: $data.Price" /></td>
<td><input type="text" data-bind="value: $data.ActualCost" /></td>
<td>
<input type="button" class="btn" value="修改" data-bind="click: $root.update" />
<input type="button" class="btn" value="刪除" data-bind="click: $root.remove" />
</td>
</tr>
</tbody>
</table>
<form class="form-horizontal" data-bind="submit: create">
<fieldset>
<legend>新增產品</legend>
<div class="control-group">
<label class="control-label">產品名稱</label>
<div class="controls">
<input type="text" name="Name" class="input-xlarge">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">儲存</button>
<button class="btn">取消</button>
</div>
</fieldset>
</form>
function ProductsViewModel() {
var baseUri = 'https://localhost:8080/knockout/';
var self = this;
self.products = ko.observableArray();
$.getJSON(baseUri + 'list', self.products);
self.create = function (formElement) {
$.post(baseUri + 'add', $(formElement).serialize(), function (data) {
if (data.success) {
var newProduct = {
Id: data.ID,
Name: formElement.Name.value,
Price: formElement.Price.value,
ActualCost: formElement.ActualCost.value
};
self.products.push(newProduct);
}
}, 'json');
};
self.update = function (product) {
$.post(baseUri + 'update', product, function (data) {
if (data.success) {
alert('修改成功');
}
}, 'json');
};
self.remove = function (product) {
$.post(baseUri + 'delete', 'productID=' + product.Id, function (data) {
if (data.success) {
self.products.remove(product);
}
}, 'json');
}
}
ko.applyBindings(new ProductsViewModel());
重點是伺服器端操作成功後,再同步更新 Knockout 的 observableArray,畫面便會自動反映最新狀態。