2017-05-02 4 views
0

나는 다음과 같은 모델이 있습니다새로 고침 뷰 모델 관찰 변화에 대한 예를 들어

var Volume = function (id, path, isactive) { 
     var self = this; 

     self.id = ko.observable(id); 
     self.path = ko.observable(path); 
     self.isactive = ko.observable(isactive); 

     self.Save = function (data) { 
      //ajax post 
     } 

     self.Update = function (data) { 
      //ajax post 
     } 
    } 

    var ViewModel = function (data) { 
     var self = this; 
     self.volumes = ko.observableArray(data.volumes.map(function (item) { 
      return new Volume(item.id, item.path, item.isActive, item.description); 
     })); 

     self.AddVolume = function() { 
      self.volumes.push(new Volume()); 
     } 
    } 

저장 또는 업데이트 후, 내가 어떤 값이 데이터베이스에 변경 되었기 때문에, 볼륨 모델에서 부모 뷰 모델을 새로 고칠를.

어떻게하면 ViewModel을 다시 초기화 할 수 있습니까?

var viewModel = new ViewModel(ko.utils.parseJson(data) || []); 
ko.applyBindings(viewModel); 
+0

부모 ViewModel_을 (를) _refresh한다는 것은 무엇을 의미합니까? –

+0

ViewModel에 새로운 데이터 바인딩하기 – capiono

+0

'Save'와'Update' ajax 콜백에서 현재'Volume'을 업데이트합니까? –

답변

0

부모 VM을 새로 고칠 필요가 없다고 생각하면 업데이트 후 값의 배열에서 특정 인덱스를 변경할 수 있습니다. 또는 getall 메소드를 호출하고 배열에서 이전 값을 지운 후에 모든 값을 푸시하십시오 (그러나 권장하지 않음). 또는 페이지를 새로 고칠 수 있습니다. 현명하게 선택하십시오

1

상위 모델에서 새 데이터를로드하고 새 데이터를 채우는 기능을 사용할 수 있습니다. 그런 다음 새 데이터를 가져올 필요가있는 곳이면 그 기능을 간단하게 호출 할 수 있습니다.

예 :

var Volume = function (data) { 
     var self = this; 

     self.id = ko.observable(data.id); 
     self.path = ko.observable(data.path); 
     self.isactive = ko.observable(data.isactive); 

     self.Save = function (data) { 
      //ajax post 
      //whenever you want to load data again you call viewModel.Load(); 
     } 

     self.Update = function (data) { 
      //ajax post 
      //whenever you want to load data again you call viewModel.Load(); 

     } 
    } 

    var ViewModel = function() { 
     var self = this; 
     self.volumes = ko.observableArray(); 
     self.Load = function(){ 
      //your ajax call or whatever you do to get the data 
      self.volumes($.map(data.volumes, function (item) { 
       return new Volume(item); 
      } 
     } 
     self.AddVolume = function() { 
       obj = {id:"",path:"",isactive:false} 
      // need to pass data to Volume model 
      self.volumes.push(new Volume(obj)); 
     } 
    } 

    var viewModel = new ViewModel(); 
    viewModel.Load(); 
    ko.applyBindings(viewModel); 

나는 당신이 당신의 상위 모델에 saveupdate 기능을 참조하기 위해 $parent 배열 객체를 사용하는 것이 좋습니다 것입니다.