2011-08-05 4 views
5

저희 웹 사이트의 검색 페이지에 녹아웃 JS를 추가하려고합니다. 현재 jQuery 대화 상자가 열리고 선택할 수있는 조건의 확인란이 여러 개 있습니다.실행 취소 할 수있는 배열을 만드는 방법은 무엇입니까?

여러 유형의 기준이있는 대화 상자가 여러 개 있습니다. 대화 상자를 열 때 "업데이트"버튼을 누르기 전까지는 확인란이 적용되지 않습니다. 취소를 클릭하거나 창을 닫으면 변경 한 내용이 되돌려지고 대화 상자는 이전 상태로 설정됩니다.

나는 this와 몇 개의 다른 게시물을 읽었습니다. 그러나 이것은 ko.observable에서만 작동하는 것으로 보이며, ko.observableArray과 함께 작동하지는 않습니다.

누구든지이 작업을 완수했거나 아이디어가 있습니까?

내가하고 싶은 것의 예 :

HTML :

<form> 
    <div> 
     <div> 
      <label><input type="checkbox" data-bind="checked: genders" value="1" />Male</label> 
      <label><input type="checkbox" data-bind="checked: genders" value="2" />Female</label> 
     </div> 
    </div> 
    <a id="buttonCancel">Cancel</a> 
    <a id="buttonUpdate">Update</a> 
</form> 
<div data-bind="text: ko.toJSON(viewModel)"></div> 

자바 스크립트 :

//wrapper to an observableArray of primitive types that has commit/reset 
ko.observableArrayWithUndo = function(initialArray) { 
    var _tempValue = ko.observableArray(initialArray.slice(0)), 
     result = ko.observableArray(initialArray); 

    //expose temp value for binding 
    result.temp = _tempValue; 

    //commit temp value 
    result.commit = function() { 
     result(_tempValue.slice(0)); 
    }; 

    //reset temp value 
    result.reset = function() { 
     _tempValue(result.slice(0)); 
    }; 

    return result; 
}; 
: 여기
var viewModel = { 
    genders: ko.observableArrayWithUndo([]) 
}; 

ko.applyBindings(viewModel); 

$('#buttonCancel').click(function(){ 
    viewModel.genders.resetChange(); 
}); 

$('#buttonUpdate').click(function(){ 
    viewModel.genders.commit(); 
    return false; 
}); 

답변

6

가 접근하는 하나 개의 방법이 될 것입니다

당신은 yourName.temp에 대한 체크 박스와 UI의 다른 부분에 대해서만 yourName. 여기

은 샘플이다 http://jsfiddle.net/rniemeyer/YrfyW/

슬라이스 (0)이 얕은 배열 복사 얻는 방법 중 하나 (또는 ​​심지어 단지 슬라이스 (가)). 그렇지 않으면 같은 배열에 대한 참조에 대해 작업을 수행하게됩니다.

+0

빠른 답변 감사드립니다. 그것이 어떻게 작동되는지 보겠습니다. –

3

을 감안할 때 HTML에 비슷한 : 당신은 기본적으로 모든 변경 후의 상태의 JSON 문자열 표현으로 실행 취소 스택을 절약과 유사한 일부 녹아웃 코드를 사용할 수

<div> 
    <button data-bind="click: function() { undo(); }">Undo</button> 
    <input data-bind="value: firstName" /> 
    <input data-bind="value: lastName" /> 
    <textarea data-bind="value: text"></textarea> 
</div> 

. 기본적으로 뷰의 모든 속성을 구독하기 위해 가짜 종속 관찰 가능 목록을 만들거나 수동으로 각 속성을 반복하고 구독 할 수 있습니다. 당신은 당신의 용도에 적용 할 수 있습니다

http://jsfiddle.net/paultyng/TmvCs/22/

:

//current state would probably come from the server, hard coded here for example 
var currentState = JSON.stringify({ 
    firstName: 'Paul', 
    lastName: 'Tyng', 
    text: 'Text' 
}) 
    , undoStack = [] //this represents all the previous states of the data in JSON format 
    , performingUndo = false //flag indicating in the middle of an undo, to skip pushing to undoStack when resetting properties 
    , viewModel = ko.mapping.fromJSON(currentState); //enriching of state with observables 


//this creates a dependent observable subscribed to all observables 
//in the view (toJS is just a shorthand to traverse all the properties) 
//the dependent observable is then subscribed to for pushing state history 
ko.dependentObservable(function() { 
    ko.toJS(viewModel); //subscribe to all properties  
}, viewModel).subscribe(function() { 
    if(!performingUndo) { 
    undoStack.push(currentState); 
    currentState = ko.mapping.toJSON(viewModel); 
} 
}); 

//pops state history from undoStack, if its the first entry, just retrieve it 
    window.undo = function() { 
     performingUndo = true; 
     if(undoStack.length > 1) 
     { 
      currentState = undoStack.pop(); 
      ko.mapping.fromJSON(currentState, {}, viewModel); 
     } 
     else { 
      currentState = undoStack[0]; 
      ko.mapping.fromJSON(undoStack[0], {}, viewModel); 
     } 
     performingUndo = false; 
}; 

ko.applyBindings(viewModel); 

는 여기 녹아웃으로 취소 N 수준의 샘플을 가지고있다.

관련 문제