Nested Models and user event contexts

2 posts, 0 answers
  1. Fabio
    Fabio avatar
    8 posts
    Member since:
    Jul 2010

    Posted 02 Sep 2016 Link to this post


    we are refactoring a rather big ViewModel in order to make it more maintainable and we are splitting it in smaller objects but we are running in some problems of context when dealing with bound events in the UI.

    Here is a bare example of our current situation.

    With a binding like this:

    <button data-bind="click: person.personMethod">personMethod</button>

    we have this ViewModel (it is TypeScript 1.8 compiled to ES5):

    /// <reference path="jquery.d.ts" />
    /// <reference path="kendo.all.d.ts" />
    class Person extends {
        public personName = "John Doe";
        private age = 65;
        constructor() { super(); super.init(this); }
        public personMethod(e) {
            alert(this.personName); /* NOT POSSIBLE as 'this' is the ROOT VIEWMODEL */
            alert(; /* NOT POSSIBLE as '' is the ROOT VIEWMODEL */
            /* How to reference 'personName'? */
            /* this is the hack that I am using now */
            const that = (this instanceof ViewModel)
                ? (<ViewModel><any>this).person
                : this;
            /* but it is ugly and it does not permit to access private properties */
            alert(that.age); /* NOT POSSIBLE BECAUSE IS PRIVATE */
    class ViewModel extends {
        public person = new Person();
        constructor() { super(); super.init(this); }

    I have written the issues into the comments.

    What are your thought on this approach? Is there a recommended way to deal with big ViewModels?



  2. Petyo
    Petyo avatar
    2444 posts

    Posted 06 Sep 2016 Link to this post


    The easiest (although, not that convenient) means to separate the concerns in this case would be nested bindings. This dojo demonstrates the necessary approach. The inconvenience: you should use templates for the nesting to take effect. 

    Telerik by Progress
    Get started with Kendo UI in days. Online training courses help you quickly implement components into your apps.
Back to Top