是否有可能影响Kendo UI中kendo.observable对象使用的数据asynchronicaly(ajax)?
使用以下代码cart.add()
触发函数并更新cart.contents
变量,但这不会影响模板,也不会刷新模板使用的数据。我希望更改cart.contents会更改模板使用的数据,例如text: quantity
和text: itemPrice
模板脚本1:
<script type="text/x-kendo-template" id="cart-preview-template">
<div id="shop-info" data-bind="attr: { class: cartContentsClass }">
<ul data-role="listview" data-bind="source: cart.contents" data-template="cart-item" id="shop-list"></ul>
<div id="shopping-cart">
<p class="total-price" data-bind="html: totalPrice"></p>
<a id="empty-cart" href="#" data-bind="click: emptyCart">empty cart</a>
</div>
</div>
</script>
模板脚本2:
<script type="text/x-kendo-template" id="cart-item">
<li class="selected-products-list">
<a data-bind="click: removeFromCart" class="view-selected-items">
<img data-bind="attr: { src: imageSource, alt: imageAlt }"
/>
</a>
<span data-bind="text: quantity"></span>
<span data-bind="text: itemPrice"></span>
</span>
</li>
</script>
模型:
var cartPreviewModel = kendo.observable({
cart: cart,
cartContentsClass: function () {
return this.cart.contentsCount() > 0 ? "active" : "empty";
},
removeFromCart: function (e) {
this.get("cart").remove(e.data);
},
emptyCart: function () {
cart.empty();
},
itemPrice: function (cartItem) {
return kendo.format("{0:c}", cartItem.item.unitPrice);
},
imageSource: function (cartItem) {
var baseUrl = "{{ absolute_url(asset('images/products/')) }}";
return baseUrl + cartItem.item.image;
},
imageAlt: function () {
return "Product image";
},
totalPrice: function () {
return this.get("cart").total();
},
proceed: function (e) {
this.get("cart").clear();
sushi.navigate("/");
}
});
对象可观察的购物车使用者:
var cart = kendo.observable({
//for testing purpose, just to show cart panel bar at start with some items.
//originally it should be: contents: []
contents: [{"item":"productID":1,"unitPrice":"111.00","image":"5.jpg"},"quantity":1}],
add: function (item) {
$.ajax({
type: 'POST',
url: '{{ path('add_product') }}',
dataType: 'json',
data: {'item': JSON.stringify(item)},
success: function (sessionCart) {
// original code:
// this.contents = sessionCart;
// code for testing, just to be sure new data is set:
this.contents = [{"item":{"productID":1,"unitPrice":"111.00","image":"5.jpg"},"quantity":1},{"item":{"productID":2,"unitPrice":"999.00","image":"8.jpg"},"quantity":1}];
},
});
},
绑定模型和模板:
kendo.bind($("#shop-info"), cartPreviewModel);
再一次,使用上面的代码cart.add()
触发函数并更新cart.contents
变量(在重新布局时),但这不会影响模板,也不会刷新模板使用的数据。
答案 0 :(得分:3)
您必须使用set()
函数更改observable上的属性值,以触发任何绑定更新。
所以改变一下:
this.contents = [
{"item":{"productID":1,"unitPrice":"111.00","image":"5.jpg"},"quantity":1},
{"item":{"productID":2,"unitPrice":"999.00","image":"8.jpg"},"quantity":1}
];
到此:
this.set("contents", [
{"item":{"productID":1,"unitPrice":"111.00","image":"5.jpg"},"quantity":1},
{"item":{"productID":2,"unitPrice":"999.00","image":"8.jpg"},"quantity":1}
]);