2016-10-13 6 views
4

녹아웃 뷰 모델을 원래 데이터로 다시 설정하는 가장 좋은 방법은 무엇입니까?knockout 원래 데이터로 뷰 모델 다시 설정

원본 데이터 json이 변경되지 않은 경우 관찰 가능 항목을 변경 한 후 어떻게 다시 설정할 수 있습니까? 페이지를 새로 고침하는 것과 같습니다.

답변

2

나는 당신의 viewModel을 "새로 고침"하는 것은 나쁜 습관이라고 생각합니다. 이처럼 새로 고칠 수 :

ko.cleanNode(document.getElementById("element-id")); 
ko.applyBindings(yourViewModel, document.getElementById("element-id")); 

그러나 나는 초기 상태로 다시 관찰 가능한을 설정합니다 "다시"라는 뷰 모델에 대한 방법을 가지고 청소기라고 생각합니다. 아마도 다음과 같습니다.

function MyViewModel() { 
    this.something = ko.observable("default value"); 
    this.somethingElse = ko.observable(0): 

    this.reset = function() { 
    this.something("default value"); 
    this.somethingElse(0); 
    } 
} 
0

ViewModels는 종종 일부 dto에서 제공하는 일부 데이터로 생성됩니다. 뷰 모델을 원래 상태로 리셋하는 것은 개인 변수의 원래 상태를 추적하여

  1. 까지 수행 할 수 있습니다.
  2. 은 리셋이 필요할 때뿐 아니라 건설시 호출 할 수있는 리셋 기능을 추가합니다.

function Car(dto) { 
 
    var originalState = dto; 
 

 
    this.brand = ko.observable(); 
 
    this.color = ko.observable(); 
 

 
    this.reset = function() { 
 
    this.brand(originalState.brand); 
 
    this.color(originalState.color); 
 
    } 
 

 
    this.reset(); 
 
} 
 

 
ko.applyBindings(new Car({ 
 
    brand: 'mercedes', 
 
    color: 'red' 
 
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 
<p> 
 
    <em>Current viewmodel values:</em> 
 
    <br/>Brand: <strong data-bind="text:brand"></strong> 
 
    <br/>Color: <strong data-bind="text:color"></strong> 
 
</p> 
 
<p> 
 
    <em>Change viewmodel values:</em> 
 
    <br/>Brand: 
 
    <input data-bind="textInput:brand"> 
 
    <br/>Color: 
 
    <input data-bind="textInput:color"> 
 
</p> 
 
<p> 
 
    <button data-bind="click: reset">Reset viewmodel values</button> 
 
</p>

관련 문제