Kendo MVVM

by lhoeppner

HTML

<script src="http://cdn.kendostatic.com/2013.3.1324/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2013.3.1324/styles/kendo.mobile.all.min.css">
<div data-role="view" id="testForm">
     <h3 data-bind="text: label"></h3>

    <p>Value of isLoggedInVM1() = <span data-bind="text: isLoggedInVM1()"></span>

        <input type="checkbox" data-bind="checked: isLoggedInVM1()" />
    </p>
    <div data-role="button" data-bind="click:logIn">Click here to Login</div>
</div>

JavaScript

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

userState = (function () {
    var userStateViewModel = kendo.observable({
        isLoggedIn: false
    });

    function loginUser() {
        userStateViewModel.set("isLoggedIn", true);
        console.log(userStateViewModel);
        console.log('Logged in');
    };

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

var viewModel1 = kendo.observable({
    label: 'ViewModel1',
    userState: userState, // if you comment this line, the view won't update
    isLoggedInVM1: function () {
        console.log("current value: " + userState.userStateViewModel.get("isLoggedIn"));
        return userState.userStateViewModel.get("isLoggedIn");
    },
    logIn: function () {
        userState.loginUser();
        console.log('After Login viewModel1.isLoggedInVM1() = ' + viewModel1.isLoggedInVM1() + ' but the binding has not updated');
    }

});

// note how the change event is triggered when you click the login button; try commenting userState above and see how it isn't triggered anymore
viewModel1.bind("change", function (e) {
    console.log("change: ");
    console.log(e);
});

console.log('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


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