我是Knockout JS的新手,學習組件如何工作。Knockout組件 - 通過組件傳遞值
我創建了兩個組件來創建員工並顯示創建的員工列表。
但我現在面臨幾個問題:
問題#1:點擊按鈕的事件沒有啓動起來
問題2:一旦被創建的員工,我想反映在另一個組件中創建的所有員工
我試圖如下樣品示於
實施例:JSFiddle
源碼:
/********************* COMPONENT-1 ************************/
ko.components.register('emp-list', {
\t \t viewModel: function(params) {
\t var self = this;
self.Name = ko.observable();
self.Name(params.EmpName.firstName + ', ' + params.EmpName.lastName);
\t \t \t
},
template: '<div class="name-container"><span data-bind="html: Name"></span></div>'
});
/********************* COMPONENT-2 ************************/
ko.components.register('emp-create', {
\t \t viewModel: function(params) {
\t 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]);
}
}
\t \t \t
},
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() {
\t \t 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>
這部分工作。當我點擊添加按鈕時,它會在員工列表組件 – user2988458
@ user2988458中添加「未定義」。這是另一個問題。你可以在這裏找到答案:https://stackoverflow.com/questions/12636695/updating-placeholder-attribute-using-knockout/12673879#12673879。 –
它與佔位符無關。這與'#issue2'有關。當你點擊添加按鈕,現在可以正常工作。但員工姓名並未反映在列表中。相反,它顯示'undefined undefined' – user2988458