Reputation: 44663
I a newbie to knockout and need some help.
I have a mvc asp.net page and when it loads I make a client side call to controller action that returns json, which I create a view model from and bind it to some markup with knockout.
This is some sample code:
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>
When the page loads a call is made to retrieve a shopping cart and bound to markup, see above.
Now when a user updates their cart on the page via a call to a controller action, returned from it is the same json object. At this point I want to update my markup with the new json object.
What changes do I need to make to above to achieve this? How can I pass the json object and not have to reapply bindings and that the markup shows the changes?
Upvotes: 0
Views: 126
Reputation: 1739
you could again call 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);
}
See this link: http://knockoutjs.com/documentation/plugins-mapping.html (Example: Using ko.mapping)
Upvotes: 3