我正在创建一个 SPA,我正在使用 knockout js 来处理 View 模型。我还使用 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
对此很满意,我在另一个文件中获得了一个 View 模型,该 View 模型附加在 mainViewModel
中,然后通过 knockout 进行绑定(bind)。
但是,在处理函数时,它会被初始化并运行,因此 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());
但它是这样说的:
Uncaught TypeError: Unable to parse bindings. Bindings value: with: $root.personViewModel.person Message: Cannot read property 'personViewModel' of undefined
最佳答案
var mainViewModel = {
init : function(){
Sammy(function () {
// initialise Sammy routes here
});
},
anotherMethod1 : function(){},
anotherMethod2 : function(){}
}
mainViewModel.init();
关于Javascript View 模型初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19890323/