gpt4 book ai didi

javascript - 在多个 viewModel 中使用 kendo 可观察属性

转载 作者:行者123 更新时间:2023-12-02 17:41:34 24 4
gpt4 key购买 nike

在使用 Kendo MVVM 框架的 Kendo 应用程序中:我有一个“全局” View 模型,它是应用程序所有部分通用的信息 - 例如UserState,它有一个属性 isLoggedIn。

许多不同的 View 和 ViewModel 访问 userState 对象(据我所知,Kendo 中 1 个 View 绑定(bind)到 1 个 ViewModel)。

例如,如果未经过身份验证,我的主页可能会显示“登录”按钮。然后,一旦您登录,所有其他屏幕的行为都会有所不同,因此每个 ViewModel 都需要引用 UserState 对象。但是,如果其中任何一个更改了它,那么所有其他 View 都应该更新,因为我使用了 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() 来更改 userStateViewModel 中 isLoggedIn 的值时,它不会更新。运行并单击按钮查看问题 - 绑定(bind)不反射(reflect)更新的值(但警报框反射(reflect))。任何帮助表示感谢,谢谢。

注意:这是 earlier question 的扩展这让我更进一步。

最佳答案

问题是 userState 是一个简单的对象,而不是 ObservableObject。因此,userStateViewmodel 可观察对象的更改事件不会触发 viewmodel1 的更改事件,并且 View 不会更新。

您可以通过将 userState 设置为 viewModel1 的属性来解决此问题,以便将其包装在可观察对象中(或者您可以将 IIFE 中的返回对象包装在可观察对象中) ):

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

看看这个 demo ;尝试注释 userState 属性,您就会看到差异。

关于javascript - 在多个 viewModel 中使用 kendo 可观察属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com