Nested Models and user event contexts

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

    Posted 02 Sep Link to this post

    Hi,

    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 kendo.data.ObservableObject {
        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(e.data.personName); /* NOT POSSIBLE as 'e.data' 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 kendo.data.ObservableObject {
        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?

     

    Thanks.

  2. Petyo
    Admin
    Petyo avatar
    2439 posts

    Posted 06 Sep Link to this post

    Hi,

    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. 

    Regards,
    Petyo
    Telerik by Progress
     
    Get started with Kendo UI in days. Online training courses help you quickly implement components into your apps.
     
  3. Kendo UI is VS 2017 Ready
Back to Top