suu*_*uue 5 javascript knockout.js
我需要使用来自两个来源的数据填充我的旅行表:从页面加载时使用GET的服务器(到用户的存档行程)和可观察值(当用户添加新行程时).我可以以某种方式合并这两个脚本,以便它们只应用绑定一次吗?现在我收到一个错误:你不能多次将绑定应用于同一个元素
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Add a trip</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="from">From</label>
<input type="text" class="form-control" id="from" name="from" placeholder="From" data-bind="value: from">
</div>
<div class="form-group">
<label for="to">To</label>
<input type="text" class="form-control" id="to" name="to" placeholder="To" data-bind="value: to">
</div>
<a class="btn btn-primary btn-lg" role="button" data-bind="click: add()" >Add</a>
</div>
</div>
<div class="panel panel-default">
<div class=panel-heading>Your trips</div>
<table class=table>
<thead>
<tr>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody data-bind="foreach: records">
<tr>
<td data-bind="text: from"></td>
<td data-bind="text: to"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="js/knockout-3.4.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var AppViewModel = function() {
this.from = ko.observable();
this.to = ko.observable();
this.records = ko.observableArray();
};
var model = new AppViewModel();
model.add = function() {
model.records.push({
from: model.from(),
to: model.to()
});
//sending data to server
var data =
{
from : this.from(), to : this.to(), date : this.date(), price : this.price(), freeSeats : this.freeSeats()
}
alert(data);
$.post("/data", data, function(response)
{
})
}
ko.applyBindings(model);
</script>
<script>
function tripModel() {
this.records = ko.observableArray([]);
$.getJSON("/usersTrips", function(data) {
self.records(data);
})
}
ko.applyBindings(new tripModel());
</script>
Run Code Online (Sandbox Code Playgroud)
提供相关元素 ID,然后将模型仅应用于那些 DOM 元素。例如,
\n\n网页:
\n\n<div id="add-trip" class="panel panel-default">\n\n<div id="your-trips" class="panel panel-default">\nRun Code Online (Sandbox Code Playgroud)\n\n和绑定:
\n\nko.applyBindings(model, document.getElementById("add-trip"));\n\nko.applyBindings(new tripModel(), document.getElementById("your-trips"));\nRun Code Online (Sandbox Code Playgroud)\n\nJSFiddle 示例:
\n\nhttps://jsfiddle.net/hellobrett/49xaqj46/1/
\n\nJSFiddle 示例走向另一个方向:
\n\nhttps://jsfiddle.net/hellobrett/49xaqj46/2/
\n\n参考:
\n\nhttp://knockoutjs.com/documentation/observables.html
\n\n\n\n如果您\xe2\x80\x99想知道 ko.applyBindings 的参数有何作用,
\n\n\n
\n- \n
第一个参数表示您想要将哪个视图模型对象与其激活的声明性绑定一起使用
- \n
或者,您可以传递第二个参数来定义要在文档的哪个部分搜索数据绑定属性。例如,ko.applyBindings(myViewModel, document.getElementById(\'someElementId\'))。这将激活限制为 ID 为 someElementId 的元素及其后代,如果您想要拥有多个视图模型并将每个视图模型与页面的不同区域关联,这非常有用。
| 归档时间: |
|
| 查看次数: |
7750 次 |
| 最近记录: |