我想在我的视图上有多个数据绑定,所以我的文本框包含正确的值,当值更改时,它调用一个函数。基本上我想在每次表单上的值更改时使用amplify.js本地存储。
代理商视图
<section class="view">
<header>
<button class="btn btn-info btn-force-refresh pull-right"
data-bind="click: refresh">
<i class="icon-refresh"></i>Refresh</button>
<button class="btn btn-info"
data-bind="click: save">
<i class="icon-save"></i>Save</button>
<h3 class="page-title" data-bind="text: title"></h3>
<div class="article-counter">
<address data-bind="text: agency().length"></address>
<address>found</address>
</div>
</header>
<table>
<thead>
<tr>
<th>Agency Name</th>
<th>Category</th>
<th>URL</th>
<th>Number of employees</th>
</tr>
</thead>
<tbody data-bind="foreach: agency">
<tr>
<td>
<!--<input data-bind="value: agencyName" /></td>-->
<input data-bind="value: agencyName, onchange: test()"/>
<td>
<input data-bind="value: category" /></td>
<td>
<input data-bind="value: Url" /></td>
<td>
<input data-bind="value:numberOfEmployees" /></td>
</tr>
<tr>
<td>Activities</td>
<td>Declared Billings</td>
<td>Campaigned Billings</td>
</tr>
<tr>
<td>
<input data-bind="value: activities" /></td>
<td>
<input data-bind="value: declaredBillings" /></td>
<td>
<input data-bind="value: campaignBillings" /></td>
</tr>
</tbody>
</table>
</section>
代理商ViewModel
define(['services/datacontext'], function (dataContext) {
//var myStoredValue = amplify.store("Agency"),
// myStoredValue2 = amplify.store("storeExample2"),
// myStoredValues = amplify.store();
var agency = ko.observableArray([]);
var initialized = false;
var save = function (agency) {
return dataContext.saveChanges(agency);
};
var vm = { // This is my view model, my functions are bound to it.
//These are wired up to my agency view
activate: activate,
agency: agency,
title: 'agency',
refresh: refresh, // call refresh function which calls get Agencies
save: save
};
return vm;
function activate() {
if (initialized) {
return;
}
initialized = true;
return refresh();
}
function refresh() {
return dataContext.getAgency(agency);
}
function test() {
alert("test");
}
});
每次输入新值时,例如
<input data-bind="value: agencyName, onchange: test()"/>
我想解雇功能测试。然后,我想将视图模型的最新数据存储到本地存储中。
有谁知道如何为此做多个绑定?
答案 0 :(得分:1)
您应该使用此绑定:
<input data-bind="value: agencyName, event: { change: $parent.onAgencyNameChanged}"/>
请注意,我使用$ parent来引用vm对象。
并为viewModel添加处理程序。
var vm = {
....
onAgencyNameChanged: function(agency){
// do stuff
}
};
return vm;
另一种解决方案可能是订阅所有代理商的agencyName。但我认为这不适合这种情况。创建vm后,您可以这样做:
ko.utils.arrayForEach(vm.agency(), function(a){
a.agencyName.subscribe(function(){
// do stuff
});
});
我希望它有所帮助。
答案 1 :(得分:0)
尝试为您必须绑定的每个元素手动订阅对象。
查看淘汰文档here中的解释和示例。