View Context for Kendo UI Mobile and MVVM

By February 25, 2014Kendo UI

When using MVVM in Kendo UI Mobile, there are times where you will need the context of the view so you can make changes to it or read values from it. You can get the current view from the application’s “view()” method, but sometimes your app is not in the global namespace if you architected it this way. Unfortunately, this does not come as a parameter for your observable functions. So here’s the trick to finding the current view:

<div id="home" data-role="view" data-model="viewModel">
    <a href="#" data-bind="click: doSomething">Do something with the view...</a>
</div>
 
<script>
var viewModel = kendo.observable({
    doSomething: function (e, view) {
        e.preventDefault();
 
        //"view" PARAMETER ABOVE DOESN'T EXIST.. BOOOOO!
        //SO GET CURRENT VIEW THIS WAY FOR LATER USE IF NEEDED
        var view = kendo.widgetInstance(
            $(e.target).closest('[data-role="view"]'));
 
        //WRITE VIEW CONTEXT TO LOG
        console.log(view);
    }
});
</script>

First I am getting the element that triggered the click event, then I crawl up the DOM hierarchy to find the view from there. Once found, I get the Kendo instance using “kendo.widgetInstance“, which can be used on ANY Kendo widget by the way 😉

Happy Coding!!

The following two tabs change content below.