2013-03-30 95 views
0

我是一個新手淘汰賽,需要一些幫助。幫助重新綁定json淘汰賽模型

我有一個mvc asp.net頁面,當它加載時,我做了一個客戶端調用控制器操作,返回json,我創建了一個視圖模型,並將其綁定到一些標記與淘汰賽。

這是一些示例代碼:

的Javascript

var CartViewModel = function (d) { 

    var self = this, 
     showCartInner = function() { 
      // code to show a container 
     }, 
     hideCart = function() { 
      // code to hide a container 
     }; 

    self.showCart = function() { 
     showCartInner(); 
    }; 

    ko.mapping.fromJS(d, {}, self); 

    self.hasItems = ko.computed(function() { 
     return self.NumberOfItems() > 0; 
    }); 

    self.count = ko.computed(function() { 
     return self.NumberOfItems(); 
    }); 

    self.qualified = ko.computed(function() { 
     return self.Qualified().length > 0; 
    }); 

    return self; 
}; 

$(document).ready(function() { 

    $.getJSON("/getcart", function (data) { 
     ko.applyBindings(new CartViewModel(data), window.document.getElementById("cart")); 
    }); 

}); 

HTML

<div id="cart"> 
<div style="display: none;" data-bind="css: { content: !hasItems() }"> 
empty Cart 
</div> 

<div style="display: none;" data-bind="css: { content: hasItems() }"> 
    <span class="loading"> 
     Look at your items 
    </span> 
</div> 

<div style="display: none;" id="hidden_menu"> 
    <div id="hidden_cart"> 
     <div class="cart-item"> 
      <div class="thumb-img inline"> 
       <img data-bind="attr: { src: Product.Image, alt: Product.Name }" /> 
      </div> 
      <div class="product-desc inline"> 
       <span class="name" data-bind="text: Product.Name"></span> 
      </div> 
      <div class="product-price" data-bind="text: Product.Price"></div> 
     </div> 
     <div class="cart-offers" data-bind="visible: qualified()"> 
      <div class="triangle-up-gray"></div> 

      <div class="cart-offer" data-bind="visible: qualified()"> 
       <div id="qualified" data-bind="foreach: { data : Qualified }"> 
        <div class="cart-offer-desc" data-bind="text: Description"></div> 
        <a class="cart-offer-action" data-bind="href: Url">View More</a> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 

在頁面加載時進行調用,以檢索的購物車並綁定到標記,參見上文。

現在,當用戶通過調用控制器動作更新其頁面上的購物車時,從它返回的是同一個json對象。在這一點上,我想用新的json對象更新我的標記。

爲了達到這個目的我需要做些什麼改變?我如何傳遞json對象,而不必重新綁定綁定,並且標記顯示了更改?

回答

3

你可以再打電話ko.mapping.fromJS

var viewModel = null; 

$(document).ready(function() { 

    $.getJSON("/getcart", function (data) { 
     viewModel = new CartViewModel(data); 
     ko.applyBindings(viewModel, window.document.getElementById("cart")); 
    }); 

}); 

function afterSomeUpdate(dataFromServer){ 
    ko.mapping.fromJS(dataFromServer, viewModel); 
} 

請參閱此鏈接:http://knockoutjs.com/documentation/plugins-mapping.html(例如:採用ko.mapping)