我有一个 Kendo Mobile 应用程序并尝试使用 Revealing Module Pattern 编写 ViewModel。
在我的 HTML 中,我将列表绑定到 gamesListDataSource。OnInit,我获取数据,然后我需要告诉我 HTML 数据源已更改。这段代码一切正常(尽管我认为我在这里做了很长的路,因为我可以以某种方式直接公开数据源)。
1)如果我注释掉这一行: GamesListViewModel.refreshGamesList(dataSource); 并取消注释这一行: this.set("gamesListDataSource", dataSource); 以便在 loadGamesList 函数中直接调用它,然后它会因“未捕获的类型错误:对象 [对象对象] 没有方法 'set'”而崩溃
我认为这与 fetch() 是异步的事实有关,但我不明白为什么调用另一个函数可以正常工作?
游戏列表.js
(function (global) {
var GamesListViewModel,
app = global.app = global.app || {};
GamesListViewModel = kendo.observable({
gamesListDataSource: {},
refreshGamesList: function (dataSource) {
//this works fine if called in a function, but not inline in loadGamesList()
this.set("gamesListDataSource", dataSource);
},
loadGamesList: function () {
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: app.configuration.getGamesListUrl,
dataType: "json",
}
}
});
console.log(dataSource.total());
dataSource.fetch(function () {
console.log('done reading');
console.log(dataSource.total());
//uncommenting this line below breaks it
//this.set("gamesListDataSource", dataSource);
GamesListViewModel.refreshGamesList(dataSource);
});
},
onInit: function (e) {
console.log("GamesListViewModel - onInit");
GamesListViewModel.loadGamesList();
}
});
app.gamesListService =
{
viewModel: GamesListViewModel
};
})(window);
游戏列表.html
<!DOCTYPE html>
<html>
<head>
<title>Games</title>
</head>
<body>
<div id="tabstrip-home"
data-role="view"
data-title="Poker Games"
data-init="app.gamesListService.viewModel.onInit"
data-model="app.gamesListService.viewModel">
<div data-role="button" data-bind="click:loadGamesList">Do it</div>
<ul class="games-list"
data-role="listview"
data-bind="source: gamesListDataSource"
data-template="games-template">
</ul>
</div>
<script type="text/x-kendo-template" id="games-template">
<div class="product">
<h4>#:Title#</h4>
</div>
</script>
</body>
</html>