我有一个js文件我打算用来控制应用中的2个视图模型。它为每个VM调用applyBindings一次。请注意console.log行:
(function () {
'use strict';
var currentFolder; // not used yet
function initializeData(folder) {
console.log('app.js initializing to ' + folder);
// Get containers for binding view models
var foldersContainer = document.getElementById('foldersPanel');
var filesContainer = document.getElementById('filesPanel');
// Create view models
var folderViewModel = new FolderViewModel(folder);
var fileViewModel = new FileViewModel(folder);
// Initialize list view models
// folderViewModel.initialize();
// fileViewModel.initialize();
// Bind view model to view
ko.applyBindings(folderViewModel, foldersContainer);
ko.applyBindings(fileViewModel, filesContainer);
}
initializeData(rootFolder); // rootfolder = global set in cshtml to web.config appSetting
})();
这是其中一个视图模型。另一个几乎完全相同。再次注意console.log行:
function Folder(name) {
var self = this;
self.Name = name;
}
function FolderViewModel(folder) {
console.log('FolderViewModel.js received folder: ' + folder);
var self = this;
self.folders = ko.observableArray([]);
self.currentFolder = ko.observable(folder);
$.getJSON('/api/folders', function (data) {
$.each(data, function (key, value) {
self.folders.push(new Folder(value.Name));
});
});
}
function onFolderClicked(folder) {
self.currentFolder(self.currentFolder() + '/' + folder.Name);
console.log(self.currentFolder());
}
这是加载页面的控制台输出(一次)。什么可能导致第二次实例化视图模型,其中'文件夹'参数未定义?