我正在尝试推送多个数据(firstname和lastname),当我计算firstname和lastname并尝试在同一个数组中推送数据时,我会抛出一个错误。以下是我的代码。
视图模型:
var viewModel = function () {
var self = this;
self.gameofthrones = ko.observableArray ([
{firstname: 'Jon', lastname: 'Snow'},
{firstname: 'Robb', lastname: 'Stark'}
]);
self.firstname = ko.observable('');
self.lastname = ko.observable('');
for (var i=0; i<self.gameofthrones().length; i++) {
self.gameofthrones()[i].fullname = ko.computed (function () {
return self.gameofthrones()[i].firstname+" "+self.gameofthrones()[i].lastname;
})
};
$('#classic').click( function() {
self.gameofthrones.push(
{firstname: $('#fn').val(), lastname: $('#pr').val()}
);
});
}
ko.applyBindings(new viewModel());
HTML视图:
<form class="" action="index.html" method="post">
<input type="text" name="name" data-bind="value: firstname" id="fn">
<input type="text" name="name" data-bind="value: lastname" id="pr">
<button id="classic" type="button" name="Submit">Submit</button>
</form>
<div data-bind="foreach: gameofthrones">
Firstname: <span data-bind="text: firstname"></span><br>
LastName: <span data-bind="text: lastname"></span><br>
Fullname: <span data-bind="text: fullname"></span><br><br>
</div>
我是Knockout JS的新手,我在这一点上陷入困境,有没有办法在observable数组中显示计算出的firstname和lastname。 谢谢你提前帮忙。
答案 0 :(得分:1)
如果你为gameofthrone数组的每个对象添加一个全名计算函数,那么当你将一个新对象推送到数组时你需要这样做,因为默认情况下它不会有一个。
有很多方法可以实现这一点,但我认为最简单的方法是创建一个函数来获取gameofthrone的可观察数组之外的全名。然后使用$parent
从foreach内部调用该函数。
var viewModel = function () {
var self = this;
self.gameofthrones = ko.observableArray ([
{firstname: 'Jon', lastname: 'Snow'},
{firstname: 'Robb', lastname: 'Stark'}
]);
self.getFullName = function(name){
return name.firstname + " " + name.lastname;
}
}
ko.applyBindings(new viewModel());
&#13;
<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.2.0/knockout-min.js"></script>
<div data-bind="foreach: gameofthrones">
Firstname: <span data-bind="text: firstname"></span><br>
LastName: <span data-bind="text: lastname"></span><br>
Fullname: <span data-bind="text: $parent.getFullName($data) "></span><br><br>
</div>
&#13;