1

我試圖在計算名和姓時試圖推送多個數據(名字和姓氏),並嘗試將數據推送到同一個數組中我被拋出錯誤。以下是我的代碼。將可觀察數據和計算數據推送到可觀察數組

視圖模型:

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> 

我是新來的淘汰賽JS和我停留在這一點上是有辦法來顯示觀察到的陣列計算的名字和姓氏。 感謝您提前幫忙。

回答

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());
<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>