knockout viewmodel和requirejs

时间:2012-11-21 14:33:41

标签: mvvm knockout.js viewmodel requirejs

我最近开始使用requirejs,当我尝试创建一个简单的viewmodel时,我得到一个奇怪的异常。例外来自knockout-2.1.0.js文件,例外是“只有可订阅的东西可以作为依赖”。

define("PageViewModel", ["knockout-2.1.0"], function(ko) {
    return function PageViewModel() {
        var self = this;
        self.visiblePage = ko.observable("StartPage");
        self.showPage = function (pageName) {
            self.visiblePage(pageName);
        };
    };
});

正如你所看到的那样,viewmodel非常简单,而且由于错误发生在knockout js文件中,似乎requirejs正常工作。我一直在关注:http://knockoutjs.com/documentation/amd-loading.html 来到该行时会发生异常:self.visiblePage = ko.observable(“StartPage”);

关于我做错的任何想法?

谢谢, 路德维希

更新: 这是包含pageviewmodel的模块:

define("ViewModelFactory", ["StorageService", "PageViewModel", "AddUnitViewModel", "AddRoomViewModel"],
function (StorageService, PageViewModel, AddUnitViewModel, AddRoomViewModel) {
    //var repositoryStorage = new StorageService();
    var createAddRoomVM = function () {
        var vm = new AddRoomViewModel();
        vm.setRepository = StorageService.getRoomRepository();
        return vm;
    };
    var createAddUnitVM = function () {
        var vm = new AddUnitViewModel();
        vm.setRepository = StorageService.getUnitRepository();
        return vm;
    };
    var createPageVM = function () {
        var vm = new PageViewModel();
        return vm;
    };

    return {
        createPageVM:createPageVM,
        createAddRoomVM: createAddRoomVM,
        createAddUnitVM: createAddUnitVM
    };
});

调用工厂的模块

define("ApplicationViewModel", ["ViewModelFactory"],
function (viewModelFactory) {
    mainVM = null;
    var initVM = function () {
        mainVM = {
            page: viewModelFactory.createPageVM(),
            addRoom: viewModelFactory.createAddRoomVM(),
            addUnit: viewModelFactory.createAddUnitVM()
        };
    };

    var getVM = function (viewName) {
        switch (viewName) {
            case "AddRoom":
                return mainVM.addRoom;
            case "AddUnit":
                return mainVM.addUnit;
            default:
                return null;
        }
    };
    var getPageVM = function () {
        return mainVM.page;
    };

    return {
        initVM: initVM,
        getVM: getVM,
        getPageVM: getPageVM,
        mainVM: mainVM
    };
});

包含applicationViewModel的类:

define("Bootstrapper", ["knockout-2.1.0", "Routing", "ApplicationViewModel"],
function (ko, routing, applicationViewModel) {
    var run = function () {
        applicationViewModel.initVM(); <-- after here mainVM.page is null
        var mainVM = applicationViewModel.mainVM;
        routing.initRouting(applicationViewModel);
        ko.applyBindings(mainVM);
        routing.showView("StartPage");
        alert("Start");
    };

    return {
        run: run
    };
})

1 个答案:

答案 0 :(得分:1)

您的问题可能是由Knockout 2.1引起的,当ko不是全局变量时,它无法正常工作。

Knockout 2.2应该可以正常工作,我从你的评论中看到这确实解决了这个问题。