2014-03-04 31 views
0

在使用Kendo MVVM框架的Kendo應用程序中:我有一個「全局」viewModel,它是應用程序所有部分共有的信息 - 例如, UserState,它有一個屬性isLoggedIn。在多視圖模型中使用kendo observable屬性

許多不同的視圖和ViewModels訪問userState對象(從我所看到的,1視圖綁定到Kendo中的1 ViewModel)。

例如,如果我的主頁未經過身份驗證,我的主頁可能會顯示登錄按鈕。然後,所有其他屏幕在登錄後的表現會有所不同,因此每個ViewModel都需要引用UserState對象。但是,如果它們中的任何一個改變了它,那麼所有其他視圖都應該更新,因爲我使用了Kendo Observable對象。這似乎並不奏效。

我成立了一個簡單的例子這裏來說明這個問題:http://jsfiddle.net/rodneyjoyce/uz7ph/11

var app = new kendo.mobile.Application(); 

userState = (function() 
{ 
    var userStateViewModel = kendo.observable({ 
                isLoggedIn: false 
               });  
    function loginUser() 
    { 
     userStateViewModel.set("isLoggedIn", true); 
     alert('Logged in'); 
    }; 

    return {    
     userStateViewModel: userStateViewModel, 
     loginUser: loginUser 
    } 
})(); 

var viewModel1 = kendo.observable({ 
    label: 'ViewModel1', 
    isLoggedInVM1: function() { 
     return userState.userStateViewModel.get("isLoggedIn"); 
    }, 
    logIn: function() 
    { 
     //when calling LoginUser from here, the binding is not updated, even though the value is changed (true) 
     userState.loginUser(); 
     alert('After Login viewModel1.isLoggedInVM1() = ' + viewModel1.isLoggedInVM1() + ' but the binding has not updated'); 
    } 

}); 

alert('Value onLoad = ' + viewModel1.isLoggedInVM1()); 

//If you uncomment this and call LoginUser from here then afterwards the binding changes to true, but not if you call it from within ViewModel1 
//userState.loginUser(); 


kendo.bind($("#testForm"), viewModel1); 

當我打電話userState.loginUser()來改變isLoggedIn的價值userStateViewModel它不會更新。運行並單擊按鈕以查看問題 - 綁定不會反映更新後的值(但警報框會這樣)。任何幫助表示感謝,謝謝。

注意:這是一個earlier question的延伸,這讓我更深入一點。

回答

2

問題是userState是一個簡單的對象,而不是ObservableObject。因此,userStateViewmodel observable的更改事件不會觸發viewmodel1的更改事件,並且視圖不會更新。

您可以通過userStateviewModel1屬性解決這個問題,所以它被包裹在可觀察到的(或者你可以換你的返回對象在IIFE可觀察):

var viewModel1 = kendo.observable({ 
    label: 'ViewModel1', 
    userState: userState, 
    isLoggedInVM1: function() { 
     return userState.userStateViewModel.get("isLoggedIn"); 
    }, 
    logIn: function() 
    { 
     userState.loginUser(); 
    }   
}); 

看看這demo;嘗試評論userState屬性,你會看到不同之處。

+0

@Rodney,我已經稍微簡化了LarsHöppner解決方案之後的原始代碼,請在此處查看:http://jsfiddle.net/OnaBai/E7ZFe/3/。我認爲理解和做同樣的事情更簡單。 – OnaBai

+0

非常感謝您的幫助! – Rodney