用户使用knockout js登录后显示用户名

时间:2014-04-17 10:13:21

标签: javascript jquery knockout.js

我有一个登录界面,用户登录屏幕后我想在仪表板顶部显示用户名,我使用淘汰赛js来做这个。我是脚本和HTML代码

var LoginViewModel = function (parantModel) {
    var self = this;
    self.userName = ko.observable();
    self.password = ko.observable(); 
    self.submit = function () {
       parantModel.dashboardViewModel.uId= self.userName;
       navigationService.navigateTo($('#dashBoardPage')); 
    }    
}
var DashboardViewModel = function(){
    var self = this;
    self.uId =  ko.observable();
}    
function PageViewModel (){
   var self = this;
   self.loginModel = new LoginViewModel(self);
   self.dashboardViewModel = new DashboardViewModel(self);  
}

function NavigationService(){
    var self = this;
    self.navigateTo = function(pageId){
        $.mobile.changePage(pageId);
    };
}

var navigationService = new NavigationService();
ko.applyBindings(new PageViewModel());

html

<div data-role="page" data-theme="a" id="loginPage" data-bind="with:loginModel">
    <div data-role="content">
        <p>
            <input type="text" class="input" placeholder="username" data-bind="value: userName"/>
            <input type="password" class="input" placeholder="Password" data-bind="value: password"/>
        </p>
        <p>
            <button data-bind='click: submit'>Login</button>
        </p>
    </div>
</div>  
<div data-role="page" data-theme="a" id="dashBoardPage" data-bind="with:dashboardViewModel">
    <div data-role="content">
     <label>User Id<span data-bind="text:uId"></span></label>
    </div>    
</div>    

从代码中删除了用户登录验证,例如http://jsfiddle.net/uderox/gY9Nt/2/

1 个答案:

答案 0 :(得分:4)

更改此行

parantModel.dashboardViewModel.uId= self.userName;

parantModel.dashboardViewModel.uId(self.userName());

pseudospeek:这样你就可以通过userName的get()来设置()uId