gpt4 book ai didi

javascript - 为什么 this.set 在 Kendo 中的这个 Javascript 函数中不起作用

转载 作者:行者123 更新时间:2023-11-30 12:48:22 24 4
gpt4 key购买 nike

我有一个 Kendo Mobile 应用程序并尝试使用 Revealing Module Pattern 编写一个 ViewModel。

在我的 HTML 中,我将列表绑定(bind)到 gamesListDataSource。 OnInit,我获取数据,然后我需要告诉我数据源已更改的 HTML。这段代码一切正常(尽管我认为我在这里做的事情很长,因为我可以以某种方式直接公开数据源)。

1) 如果我注释掉这一行:GamesListViewModel.refreshGamesList(dataSource); 并取消注释这一行:this.set("gamesListDataSource", dataSource); 以便直接在 loadGamesList 函数中调用它,然后它因“未捕获的类型错误:对象 [对象对象] 没有方法‘设置’”而失败

我认为这与 fetch() 是异步的事实有关,但我不明白为什么调用另一个函数可以正常工作?

gamesList.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);

gamesList.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>

最佳答案

看一下kendo.data.js中的数据源fetch方法;本质上,它会做这样的事情:

fetch: function (callback) {
var that = this;

...

if (fetchSuccessful) {
if (callback) {
// as you can see here, when invoking your callback,
// the code binds "this" to the data source instance
// you called .fetch() on
callback.call(that, e);
}
}
},

此模式用于许多其他接受回调的方法 - 使用 Kendo UI,您通常可以期望 this 是您调用方法的小部件。您的其他调用有效,因为您引用了 GamesListViewModel 变量而不是 this。你也可以这样做:

GamesListViewModel.set("gamesListDataSource", dataSource);

关于javascript - 为什么 this.set 在 Kendo 中的这个 Javascript 函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21825621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com