2017-03-21 11 views
0

私はあまり単純なビューモデルを持っています。私はobservableArray を持っています。これは、viewModel.filterCustomersを呼び出してフィルタリングできます。これは正常に動作し、私のビューは更新されます。今私はgetCachedCustomersを呼び出すと、observableArray customersを復元し、UIを更新する関数を作成したいと思います。フィルタリング後にobservableArrayを更新します。

私が呼び出す場合:

viewModel.customers(viewModel.cachedCustomers()); 

viewModel.customers()は更新されません。配列には依然としてフィルタリングされた要素があります。

これは私の問題の「ダムダウン」バージョンです。どんな助けもありがとうございます。

var viewModel = { 
      PageName: "Editor",        
      filteredCustomers: ko.observableArray([]), 
      cachedCustomers: ko.observableArray([]),    
      customers: ko.observableArray([]), 
      applyFilter: ko.observableArray([]),    

      getCachedCustomers: function() { 

       viewModel.customers(viewModel.cachedCustomers()); 
       viewModel.customers.valueHasMutated(); 
       console.log(viewModel.cachedCustomers()); 

      } 

     }; 

     viewModel.filterCustomers = function() { 

      var filter = $('#txtFilter').val(); 
      if (filter.length < 1) { 
       return; 
      } 
      viewModel.applyFilter = ko.computed(function() { 
       viewModel.customers(ko.utils.arrayFilter(viewModel.customers(), function (item, data) { 
        return stringStartsWith(item.CustomerNumber().toLowerCase(), filter.toLowerCase()) || stringStartsWith(item.CustomerName().toLowerCase(), filter.toLowerCase()); 
       })); 
      }, viewModel); 

     }; 

答えて

2

あなたのビューモデルを必要以上に複雑にしているような気がします。あなたが必要なもの、filterCustomers方法を持っている必要はありません、私の意見では

filteredCustomersが観察計算することです。

function myViewModel() { 
    var self = this; 
    this.customers = ko.observableArray([]); 
    //use this observable in your markup to retrieve the filter 
    this.searchFilter = ko.observable(''); 
    this.filteredCustomers = ko.computed(function() { 
     var tempFilteredCustomers = self.customers(); 
     if (typeof self.searchFilter() == 'string' && self.searchFilter().length > 0) { 
      //apply filter here on tempFilteredCustomers 
     } 
     return tempFilteredCustomers; 
    } 
} 
関連する問題