2017-02-22 70 views
0

我需要一些幫助在這裏:https://jsfiddle.net/vhaurnpw/淘汰賽觀察到的數組不會重新渲染我的名單

我想做一個簡單的列表,這是在頂部和更新自身的輸入過濾..

JS /基因敲除:

var viewModel = { 
    query: ko.observable(''), 
    places: ko.observable(data), 

    search: function(value) { 
     viewModel.places = []; 
     console.log(value) 

     for (var i = 0; i < data.length; i++) { 

      if(data[i].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) { 
       viewModel.places.push(data[i]); 
      } 
       console.log(viewModel.places); 
     } 
    } 
}; 

viewModel.query.subscribe(viewModel.search); 

ko.applyBindings(viewModel); 

HTML:

<form acion="#" data-bind="submit: search"> 
<input placeholder="Search" type="search" name="q" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off"> 
</form> 

<ul data-bind="foreach: places"> 
    <li> 
    <span data-bind="text: name"></span> 
    </li> 
</ul> 

將顯示列表,但當您鍵入內容時,它不會顯示結果。

相反,當你查找控制檯,你會看到console.log,它更新得很好!

那麼我如何刷新我的HTML? :(

+1

通過調用它們可觀測值。這行'viewModel.places = [];'需要'viewModel.places([])''。 – user3297291

+0

謝謝!那個和可觀察的陣列得到它的工作! – Shouldz

回答

2

有以下代碼中的問題。

  1. places需求是一個ObservableArray,而不是可觀察到的,這樣就可以追蹤從可觀察陣。所以,改變代碼的添加/刪除從places: ko.observable(data)places: ko.observableArray(data),
  2. viewModel.places是功能,所以當你像指定另一個viewModel.places = []值,它分配一個空數組到viewModel.places。爲了修改viewModel.places的價值,你需要把它調用一個函數升IKE viewModel.places([]);

注:您的代碼不會添加回數據的情況下,該文本框被清除,我希望你有解決這個問題,你可以解決這個問題爲好。

完整的工作代碼:

var data = [ 
 
\t \t \t { name: 'Isartor'}, 
 
\t \t \t { name: 'Sendlinger Tor'}, 
 
\t \t \t { name: 'Marienplatz'}, 
 
\t \t \t { name: 'Stachus'}, 
 
\t \t \t { name: 'Bayerischer Rundfunk'}, 
 
\t \t \t { name: 'Google München'}, 
 
\t \t \t { name: 'Viktualienmarkt'}, 
 
\t \t \t { name: 'Museumsinsel'}, 
 
\t \t \t { name: 'Tierpark Hellabrunn'}, 
 
\t \t \t { name: 'Allianz Arena'}, 
 
\t \t \t { name: 'Olympia-Park'}, 
 
\t \t \t { name: 'Flaucher-Insel'} 
 
\t \t \t \t \t ]; 
 

 
var viewModel = { 
 
\t \t query: ko.observable(''), 
 
\t \t places: ko.observableArray(data), 
 

 
\t \t search: function(value) { 
 
\t \t \t viewModel.places([]); 
 
\t \t \t console.log(value) 
 

 
\t \t \t for (var i = 0; i < data.length; i++) { 
 

 
\t \t \t \t if(data[i].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) { 
 
\t \t \t \t \t viewModel.places.push(data[i]); 
 
\t \t \t \t } 
 
\t \t \t \t \t console.log(viewModel.places); 
 
\t \t \t } 
 
\t \t } 
 
}; 
 

 
viewModel.query.subscribe(viewModel.search); 
 

 
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 
<form acion="#" data-bind="submit: search"> 
 
    <input placeholder="Search" type="search" name="q" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off"> 
 
</form> 
 

 
<ul data-bind="foreach: places"> 
 
    <li> 
 
     <span data-bind="text: name">asd</span> 
 
    </li> 
 
</ul>

+0

謝謝,這樣做!它很棒! – Shouldz