1

에 Ko.observable에 바인딩되지 않은 :값이 내가 텍스트 상자에 바인딩하는 데 사용하는 코드입니다 knockout.js

var CategoryViewModel = { 
    categoryModel: ko.observable({ 
     categoryId: ko.observable(), 
     categoryName: ko.observable(), 
     active: ko.observable() 
    }), 
    GetCategoryById: function (data, event) { 
     CategoryViewModel.ClickId(event.target.id); 
     var ajaxUrl = ApplicationRootUrl("GetCategoryById", "Category") + "/" + CategoryViewModel.ClickId(); 

     $.ajax({ 
      type: "GET", 
      contentType: "application/json; charset=utf-8", 
      url: ajaxUrl, 
      dataType: "json", 
      success: function (data) { 
       if (data.isSuccess) { 
        // This value got bind to textbox 
        CategoryViewModel.categoryModel(data.data); 
       } 
      }, 
      error: function (err) { 

      } 
     }); 
    }, 
    CategoryAddButton: function() { 
     CategoryViewModel.categoryModel(); 
     $('#addCategoryModel').modal('toggle'); 
    }    
}; 

$(document).ready(function() { 
    ko.applyBindings(CategoryViewModel, document.getElementById("categoryMain")); 
}); 

CategoryAddButton 방법은 버튼 클릭 호출됩니다. 이 메서드에서 모델 값을 비우려고합니다.

<input type="text" name="CategoryName" class="form-control" placeholder="Enter Category Name" data-bind="textinput: categoryModel().categoryName"> 

텍스트 상자 값이 아약스 호출에 바인딩됩니다 : 여기

는 HTML입니다. 그러나 CategoryAddButton 메서드를 호출 한 후에는 값이 텍스트 상자에 바인딩되지 않습니다.

답변

3

먼저 내가 작성한 것으로부터보기 모델을 만드는 다른 방법을 사용하는 것이 좋습니다. 비록 초보자의 예제가 똑같은 경우에도 단순성을 위해서만 사용됩니다. 실제로는 객체 모델로 뷰 모델을 만드는 것이 좋지 않습니다. 다른 많은 중복 중 here, herehere 게시 됨으로 동일한 작업의 다른 속성에 액세스하는 것이 그 작업이 얼마나 사소한 지에도 불구하고 상당히 더러워 질 수 있기 때문입니다.

이 문제를 해결하려면 생성자와 new 연산자를 사용해야합니다. 이렇게하면 개체를 훨씬 쉽게 조작 할 수 있기 때문입니다. 그러나이 코드는 생성자와 new 개체 구문을 사용하여 혼자서 문제를 해결할 수는 없으며 더 깨끗한 코드를 작성하기위한 지침으로 만 추가했습니다.

질문에 다시 돌아가 보겠습니다. 코드가 작동하지 않는 이유를 확인하려면 바인딩이 작동 할 때 데이터를 조작하는 방법과 그렇지 않은 경우를 살펴보십시오.

AJAX 호출이 성공한 후 값이 제대로 업데이트되어 바인딩이 작동한다고 말했습니까? 이는 AJAX 호출의 success 콜백에서 실제로 객체를 categoryModel에 전달하기 때문입니다. 그러나, 당신이 그것을 전달하는 것은 관측 가능하지만 단순한 객체 인 반면, 처음에는 관찰 할 수있는 속성으로 생성한다는 점을 지적하고자합니다. 그래서 거기에서도 문제가 발생할 수 있습니다.

단추를 클릭 한 후에도 값이 업데이트되지 않았다고합니다. 나는 당신이 여기에서 성취하기를 원하는 것이 무엇인지 정말로 확신하지 못한다. 무엇을 표시하고 싶고 어디에서 데이터를 가져와야합니까? 이 코드 줄 때문에 당신이 쓴 :

CategoryViewModel.categoryModel(); 

는 단순히 게터 - 그것은 어떤 방식으로 객체를 변경하지 않습니다, 당신은 단지 그 값을 읽고있다. 실제로 그것을 수정하지 않으면 물론 아무것도 바뀌지 않을 것입니다.

그래서 모든 것을 구현할 수있는 방법을 알려 드리겠습니다. 자바 스크립트 객체 생성자에 대해 자세히 읽고 knockout을 올바르게 사용하는 방법을 제안합니다.

function categoryViewModel() { 
    var self = this; 

    // Don't wrap these in another observable, that's totally needless. 
    this.categoryId = ko.observable(null); 
    this.categoryName = ko.observable(null); 
    this.active = ko.observable(true); 

    // You could actually define this on the prototype 
    // but I don't want to make it even more complicated 
    this.GetCategoryById = function(categoryId) { 
     // You could do this if the value passed can either be a plain value 
     // or an observable; ko will return the actual value to you. 
     var catId = ko.utils.unwrapObservable(categoryId); 

     var ajaxUrl = ApplicationRootUrl("GetCategoryById", "Category") + "/" + catId; 

     $.ajax({ 
      type: 'GET', 
      contentType: "application/json; charset=utf-8", 
      url: ajaxUrl, 
      dataType: "json", 
      success: function(data) { 
       if (data.isSuccess) { 
        // Correct the object references according to 
        // the structure of the response if needed. 
        self.categoryId(data.data.id); 
        self.categoryName(data.data.name); 
        self.active(data.data.isActive); 
       } 
      }, 
      error: function(err) { 
      } 
     }); 
    }; 

    this.CategoryAddButton = function() { 
     self.categoryId(null); 
     self.categoryName(null); 
     self.isActive(true); // If you want to default to true. 
     $('#addCategoryModel').modal('toggle'); 
    }; 
}; 

$(document).ready(function() { 
    ko.applyBindings(new categoryViewModel(), document.getElementById("categoryMain")); 
}); 

그리고 당신의 HTML이 될 수있다 :

GetCategoryById 기능에 관해서는
<input type="text" name="CategoryName" class="form-control" data-bind="textInput: categoryName" /> 

, 당신이 할당 된 경우도 좋을 것이라고 함수 프로토 타입, 오히려 각각에 "복사"를 할당하는 것보다 및 생성 된 모든 객체. 그러나 당신이 당신의 뷰 모델의 인스턴스를 오직 하나만 가질 것이라고 가정하기 때문에, 나는 지금 그것을 범위 밖이라고 생각할 것입니다.

관련 문제