我是 Knockout JS 的新手,正在学习组件的工作原理。
我创建了两个组件来创建员工并显示已创建员工的列表。
但我面临几个问题:
问题#1: 按钮的单击事件未触发
问题#2:一旦创建了员工,我想在另一个组件中反映所有创建的员工。
我已经尝试如下示例所示
示例: JSFiddle
源代码:
/********************* COMPONENT-1 ************************/
ko.components.register('emp-list', {
viewModel: function(params) {
var self = this;
self.Name = ko.observable();
self.Name(params.EmpName.firstName + ', ' + params.EmpName.lastName);
},
template: '<div class="name-container"><span data-bind="html: Name"></span></div>'
});
/********************* COMPONENT-2 ************************/
ko.components.register('emp-create', {
viewModel: function(params) {
var self = this;
self.firstName = ko.observable(),
self.lastName = ko.observable(),
self.EmpList = ko.observableArray(),
self.AddEmp = function()
{
alert('1');
self.Emplist.push(self.firstName() + ' ' + self.lastName());
for( i=0; i< self.Emplist(); i++)
{
alert(self.Emplist()[i]);
}
}
},
template: '<div class="create"><input type="text" placeholder="First name" data-bind="text: firstName" /><input type="text" data-bind="text:lastName" placeholder="Last name" /><input type="button" value="Add" data-bind="click: $root.AddEmp" /></div>'
});
/******************** VIEW MODEL ************************/
var vm = function() {
var self = this;
self.Emps = [{'Details': {firstName: 'First Name-A', lastName: 'Last Name-A'}},
{'Details': {firstName: 'First Name-B', lastName: 'Last Name-B'}}];
}
ko.applyBindings(new vm());
.name-container{
padding: 5px;
margin: 2px;
background-color: #cacaca;
border: 1px solid #888;
border-radius: 5px;
}
.name-container span {
margin: 5px;
}
body {
font-family: arial,sans-serif;
font-size: 13px;
}
.action {
cursor: pointer;
color: blue;
text-decoration: underline;
}
.create {
background-color: #cacaca;
padding: 5px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div data-bind='component: {name: "emp-create"}'>
</div>
<div data-bind='foreach: Emps'>
<div data-bind='component: {
name: "emp-list",
params: {EmpName: Details}
}'></div>
</div>