This is a migrated thread and some comments may be shown as answers.

Nested Models and user event contexts

1 Answer 85 Views
MVVM
This is a migrated thread and some comments may be shown as answers.
Fabio
Top achievements
Rank 1
Fabio asked on 02 Sep 2016, 04:24 PM

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.

1 Answer, 1 is accepted

Sort by
0
Petyo
Telerik team
answered on 06 Sep 2016, 07:01 AM
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.
 
Tags
MVVM
Asked by
Fabio
Top achievements
Rank 1
Answers by
Petyo
Telerik team
Share this question
or