Javascript ViewModel初始化

我正在创建一个SPA,我正在使用knockout js来查看模型。 我也使用Sammy js进行路由和导航。

我使用learn.knoutoutjs.com作为如何创建SPA的先行者。 在此,他们将主视图模型作为函数:

function mainViewModel() { // insert other view models in here Sammy(function () { // initialise Sammy routes here }); } 

我在代码中使用的是对象而不是函数:

 var mainViewModel = { // insert other view models in here } 

出于个人喜好,我这样做。 ko.applyBindings ,我在一个不同的文件中有一个视图模型,它被附加在mainViewModel然后它被敲除绑定。

但是,在处理函数时,它会被初始化并运行,因此Sammy(function () {})被触发。 使用var方法,它没有,我怎么做到这一点,因为在Sammy(function () {})它需要使用mainViewModel但显然它在页面加载时尚未初始化起来。

如何将Sammy放入var方法并使其初始化?

我有这个代码:

 var personViewModel = { init: function () { this.person = ko.observable(new this.personModel({firstname:"callum", lastname:"linington"})); }, personModel: function (data) { var self = this; self.firstname = ko.observable(data.firstname); self.lastname = ko.observable(data.lastname); self.fullname = ko.computed(function () { return this.firstname + " " + this.lastname; }, this); }, person: new Object() }; 

然后:

 var mainViewModel = { init: function () { // do sammy stuff }, personViewModel: personViewModel.init() } ko.applyBindings(mainViewModel.init()); 

但它是这样说的:

未捕获的TypeError:无法解析绑定。 绑定值:with:$ root.personViewModel.person消息:无法读取未定义的属性’personViewModel’

  var mainViewModel = { init : function(){ Sammy(function () { // initialise Sammy routes here }); }, anotherMethod1 : function(){}, anotherMethod2 : function(){} } mainViewModel.init();