Javascript ViewModel初始化 [英] Javascript ViewModel Initialisation

查看:355
本文介绍了Javascript ViewModel初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating an SPA, I'm using knockout js for the view model stuff. I'm also using Sammy js for the routing and naviagtion.

我使用learn.knoutoutjs.com作为如何创建SPA的初学者。在这里他们将主视图模型作为函数:

I used learn.knoutoutjs.com for the starters of how to create an SPA. In this they have the main view model as a function:

function mainViewModel() {
    // insert other view models in here

    Sammy(function () {
       // initialise Sammy routes here
    });
}

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

I'm using an object rather than a function in my code:

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

我这样做是出于个人喜好。 ko.applyBindings 对此有用处,我在 mainViewModel 然后它被敲除绑定。

I'm doing it this way out of personal preference. ko.applyBindings works a treat with this, and I've got a view model in a different file getting attached in the mainViewModel then it is binded by knockout.

然而,当处理一个函数时,它会被初始化并运行,所以 Sammy(function() {})被解雇了。使用 var 方法,它没有,我怎么做到这一点,因为在 Sammy(function(){})它需要使用 mainViewModel 但显然在页面加载时尚未初始化。

However, when dealing with a function, it gets initialised and ran, so Sammy(function () {}) gets fired. Using the var method, it doesn't, how do I get it to do this, because inside the Sammy(function () {}) it requires the use of the mainViewModel but obviously it hasn't been initialised when the page is loaded up.

如何在 var 方法中放入 Sammy 并让它初始化?

How do I put Sammy in the var method and get it to initialise?

我有这段代码:

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消息:无法读取属性
'undeViewModel'未定义

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 ViewModel初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆