问题
In a Kendo app using the Kendo MVVM framework: I have a "global" viewModel which is information that is common to all parts of the app - e.g. the UserState, which has a property isLoggedIn.
Many different Views and ViewModels access the userState object (from what I can see, 1 View is bound to 1 ViewModel in Kendo).
For example, my home page might show the Login button if they are not authenticated. Then all the other screens behave differently once you are logged in, so each ViewModel needs to reference the UserState object. However, if any of them change it then all other Views should update as I used a Kendo Observable object. This does not seem to work.
I set up a simple example here to illustrate the problem: http://jsfiddle.net/rodneyjoyce/uz7ph/4/
var app = new kendo.mobile.Application();
var userStateviewModel = kendo.observable({
isLoggedIn: false,
});
var viewModel1 = kendo.observable({
label: 'From ViewModel1',
isLoggedInVM1: userStateviewModel.isLoggedIn
});
userStateviewModel.set('isLoggedIn', true);
//viewModel1.set('isLoggedInVM1', userStateviewModel.isLoggedIn);
alert(viewModel1.isLoggedInVM1);
kendo.bind($("#testForm"), viewModel1);
userStateViewModel is used by many different Views, so in ViewModel1 I expose the iSloggedIn property and bind to it in the view (starts off as false).
Then the code sets it to true in userStateViewModel - so I need all observiing instances of it to change to true - but this does not work. If I comment out this line of code //viewModel1.set('isLoggedInVM1', userStateviewModel.isLoggedIn);
then it will work, but this defeats the point of an observable as I don't know which of the 10 ViewModels will update it and when, but all views need to update the new value...
回答1:
When you do isLoggedInVM1: userStateviewModel.isLoggedIn
in viewModel1
initialization, you are assigning the value that it has at that precise moment in time (false
). Instead, use a function that gets the value.
var viewModel1 = kendo.observable({
label: 'From ViewModel1',
isLoggedInVM1: function() {
return userStateviewModel.get("isLoggedIn");
}
});
Then, when trying to check isLoggedInVM1
do:
alert(viewModel1.isLoggedInVM1());
or
<h3 data-bind="text: isLoggedInVM1()"></h3>
Your JSFiddle modified here: http://jsfiddle.net/OnaBai/uz7ph/6/
来源:https://stackoverflow.com/questions/22111653/how-to-use-a-kendo-observable-property-in-multiple-viewmodels