每次尝试将ObservableArray绑定到ListView时,我都会有一个NativeScript应用程序崩溃。
当我注释掉我的standings.js文件的第9行时,登录功能运行,并且积分加载功能运行,但当我取消注释该行时整个应用程序崩溃,登录功能甚至不运行
这是standings.js:
var dialogsModule = require("ui/dialogs");
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var StandingsListViewModel = require("../../shared/view-models/standings-list-view-model");
var page;
var standingsList = new StandingsListViewModel([]);
var pageData = new Observable({
standingsList: standingsList
});
exports.loaded = function(args) {
page = args.object;
page.bindingContext = pageData;
standingsList.load();
};
standings.xml:
<Page loaded="loaded">
<GridLayout rows="auto, *" columns="2*, *">
<Label id="header" text="Standings" colSpan="2" horizontalAlignment="center"/>
<ListView items="{{ standingsList }}" id="standingsList" row="1" colSpan="2">
<ListView.itemTemplate>
<Label text="{{ place }}" horizontalAlignment="left" verticalAlignment="center"/>
<Label text="{{ username }}" col="2" horizontalAlignment="left" verticalAlignment="center"/>
</ListView.itemTemplate>
</ListView>
</GridLayout>
</Page>
and standings-list-view-model.js:
var config = require("../../shared/config");
var fetchModule = require("fetch");
var ObservableArray = require("data/observable-array").ObservableArray;
function StandingsListViewModel(items) {
var viewModel = new ObservableArray(items);
viewModel.load = function() {
console.log("hit");
var url = config.apiURI + "getStandings.cfm?weekid=397";
return fetch(url)
.then(handleErrors)
.then(function(data) {
var parsedData = JSON.parse(data._bodyInit);
var users = parsedData.users;
users.forEach(function(standing) {
viewModel.push({
place: standing.place,
username: standing.username
});
});
console.log(viewModel._array[0].username);
})
.catch(function(error) {
console.log("ERROR: " + error);
});
};
return viewModel;
}
function handleErrors(response) {
if (!response.ok) {
console.log(JSON.stringify(response));
throw Error(response.statusText);
}
return response;
}
module.exports = StandingsListViewModel;
非常感谢有关如何更好地调试的任何帮助或想法。
答案 0 :(得分:0)
我认为问题出在var standingsList = new StandingsListViewModel([]);
。使用new
将创建变量类型的对象。但是在这里你将StandingListViewModel()
定义为一个函数,而不是一个可能没有像你期望的那样返回standingList
的类。将该行替换为:
var standingsList = StandingsListViewModel([]);