我想发送视图和数据的两个请求,然后当视图和数据请求响应时,它们需要绑定。我为此使用了setInterval。但我不知道这是不正确的方法。
有时我需要更新大部分ViewModel数据。我无法弄清楚如何更新这些海量数据。
使用此代码,我可以获得视图和数据。但我不能在viewModel中使用数据。因为如果我在绑定后尝试更新数据,我不知道该怎么做。
有什么建议吗?
app.js中的
crossroads.addRoute('/cart', function () {
require(['cart'], function () {
cart.init();
});
});
in cart.js
define(['jquery', 'knockout'], function($, ko) {
var cart = {
viewLoaded: false,
dataLoaded: false,
template: '',
cartData: {},
container: '#container',
// Gets external template
getView: function () {
$.ajax({
...
success: function (response) {
cart.viewLoaded = true;
$(cart.container).html(response);
}
});
},
// Gets data
getCart: function () {
$.ajax({
...
success: function (response) {
cart.dataLoaded = true;
cart.cartData = response;
}
});
},
ViewModel: function () {
var self = this;
self.cartId = ko.observable();
self.products = ko.observableArray([]);
.
.
.
},
// Checks both template and data are loaded
bindings: function () {
var loadControl = setInterval(function() {
if (cart.viewLoaded && cart.dataLoaded) {
ko.applyBindings(new cart.ViewModel(), $(cart.container)[0]);
clearInterval(loadControl);
}
}, 100);
},
init: function () {
this.getView();
this.getCart();
this.bindings();
}
};
return cart;
});
答案 0 :(得分:0)
我使用回调函数而不是间隔。当用户更改URL时,我会删除DOM元素和绑定,如下所示:
app.js中的
var stepCart = crossroads.addRoute('/cart', function () {
require(['cart'], function () {
cart.init();
});
});
stepCart.switched.add(function () {
cart.stopEvents();
});
in cart.js
define(['jquery', 'knockout'], function($, ko) {
var cart = {
.
.
.
// Gets external template
getView: function (callback) {
$.ajax({
...
success: function (response) {
cart.viewLoaded = true;
$(cart.container).html(response);
if (typeof callback === 'function') {
callback();
}
}
});
},
// Gets data
getCart: function (callback) {
$.ajax({
...
success: function (response) {
cart.dataLoaded = true;
cart.cartData = response;
if (typeof callback === 'function') {
callback();
}
}
});
},
.
.
.
// Removes DOM elements and bindings
stopEvents: function () {
ko.cleanNode($(cart.container).get(0));
$(cart.container).empty();
this.viewLoaded = false;
this.dataLoaded = false;
},
// Checks both template and data are loaded
bindings: function () {
if (cart.viewLoaded && cart.dataLoaded) {
ko.applyBindings(new cart.ViewModel(cart.cartData), $(cart.container)[0]);
}
},
init: function () {
this.getCart(cart.bindings);
this.getView(cart.bindings);
}
};
return cart;
});