NotifyPropertyChange on Nativescript

If you like me are developing apps with nativescript core with typescript, probably know the PropertyChange event behind the MVVM (Yes, I love NativeScript core with TS because reminds me to my love for WPF/UWP development on Windows).

How on Windows, your class must implement the INotifyPropertyChange interface, in Nativescript specific case you just need to extends the Observable class.

Here how you can notify that a property is changed (we are assuming that we have a ViewModel with the property “Clicked” ad “ClickedTitle” in it.

public Clicked: number = 0;
public ClickedTitle: string = "";
// note that this is an attribute, not a property
public UpdateUI()
{
   this.Clicked = this.Clicked++;
   this.ClickedTitle = "You have clicked " + this.Clicked + " times";
   this.notifyPropertyChange("Clicked", this.Clicked);
   this.notifyPropertyChange("ClickedTitle", this.ClickedTitle);
}

Has you can see, the notifyPropertyChange event is a bit ugly to write, too long and too redundant.

In my apps I use to create a common ViewModel that extends Observable (it is userful also for login tokens, common functions, etc.) and implements a methods called npc that is used for notify property change events.

export class ViewModel extends Observable
{
    /**
     * Notify changes for a property
     * @param props array with props to notify
     */
    public npc(prop: string | string[]): void
    {
        if (typeof prop === "string")
            this.notifyPropertyChange(prop, this.get(prop));
        else
        {
            prop.forEach(item =>
            {
                this.notifyPropertyChange(item, this.get(item));
            });
        }
    }
}

If we extends our ViewModels with ViewModel class instead of Observable, we can access to “npc” function, lets see the difference between previous and current code.

public Clicked: number = 0;
public ClickedTitle: string = "";
// note that this is an attribute, not a property
public UpdateUI()
{
   this.Clicked = this.Clicked++;
   this.ClickedTitle = "You have clicked " + this.Clicked + " times";
   // we can do this
   this.npc("Clicked");
   this.npc("ClickedTitle");
   // or better 
   this.npc(["Clicked", "ClickedTitle"]);
}

This isn’t a revolution, just it’s a bit more elegeant and a bit less redundant of the original style.

NOTE: For the example we are using attributes instead properties (the concept is that the accessories, from ES2015, are very similar to C# properties). Honestly I don’t know if .NET notation is appropriate for js/ts case, but however the property change events works for both.