Is it possible for ko.mapping to elegantly encompass both getters and setters?

Exploring the fusion of Knockout and TypeScript. Check out this code snippet:

class Person
{
    public FirstName:string = "John";
    public LastName: string = "Doe";

    public get FullName(): string
    {
        return this.FirstName + " " + this.LastName;
    }

    public set FullName(fullName: string): void
    {
        var names = fullName.split(" ");
        this.FirstName = names[0];
        this.LastName = names[1];
    }
}

This can be transformed into:

var Person = (function()
{
    function Person()
    {
        this.FirstName = "John";
        this.LastName = "Doe";
    }

    Object.defineProperty(
        Person.prototype,
        "FullName",
        {
            get: function()
            {
                return this.FirstName + " " + this.LastName;
            },
            set: function(fullName)
            {
                var names = fullName.split(" ");
                this.FirstName = names[0];
                this.LastName = names[1];
            },
            enumerable: true,
            configurable: true
        });

    return Person;
})();

Experiment further with:

var mapped = ko.mapping.fromJS(new Person());
mapped.FirstName("Steve");
console.log("Expected 'Steve Doe', got :", mapped.FullName()); //John Doe
mapped.FullName("John Travolta");
console.log("Expected 'Travolta', got :", mapped.LastName()); //Doe

However, there seems to be an issue. Is there a way for ko.mapping to comprehend getters and setters in a versatile manner?

Answer №1

If you want more control, you can define the fullName as a computed function like this:

var Person = function() {
  var self = this;

  self.firstName = ko.observable('Jane');
  self.lastName = ko.observable('Smith');

  self.fullName = ko.computed({
    read: function() {
      return self.firstName() + ' ' + self.lastName();
    },
    write: function(name) {
      if( name ) {
        var names = name.split(' ');
        self.firstName(names[0]);
        self.lastName(names[1]);
      }
    }
  });
};

In my experience, using ko.mapper with complex objects can be tricky, so I prefer handling it manually. It's not that difficult to do and gives you greater flexibility.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring uniqueness in an array using Typescript: allowing only one instance of a value

Is there a simple method to restrict an array to only contain one true value? For instance, if I have the following types: array: { value: boolean; label: string; }[]; I want to make sure that within this array, only one value can be set to t ...

Issue detected in loading ./styles.css in Angular 6

I'm a beginner with Angular 6 and encountered this error in my project: ERROR in multi ./node_modules/bootstrap/dist/css/bootstrap.min.css ./styles.css Module not found: Error: Can't resolve 'C:\Users\User\e-CommerceWebsite& ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

The formio onchange event may result in an undefined object

Encountering an issue here: Error: src/app/app.component.html:1:30 - error TS2532: Object is possibly 'undefined'. 1 <form-builder [form]="form" (change)="onChange($event)"></form-builder> while working on my for ...

Stepper that is vertical combined with table information

I am currently facing a unique challenge with a component I'm trying to create. It's a combination of a vertical Stepper and a Datagrid. My goal is to group specific table sections within the content of a vertical Stepper, purely for data visual ...

How can we add a key:value pair at a specific position in an array in Angular 2 using Typescript?

Is there a way to insert a key value pair at a specific index in an array? I am currently struggling with this task. Here is the code I have been working on: this.quiz.push( { "question-no":this.no, "Ans":this.ans } I require this functionality to ...

Save the entire compiler output as a text or CSV file by using the "strict":true compiler option in TypeScript

The tsconfig.json file in my Visual Studio project includes the following settings: { "CompileOnSave":false, "CompilerOptions":{ "strict": true, "skipLibCheck":true }, "angularCompilerOptions":{ "fullT ...

Consolidating Typescript modules into a single .js file

Recently, I was able to get my hands on a TypeScript library that I found on GitHub. As I started exploring it, I noticed that there were quite a few dependencies on other npm packages. This got me thinking - is there a way to compile all these files int ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

Typescript raises an error when providing a potentially null value (that is not null) to an unnamed callback function

When dealing with a property that starts as null, how can I pass it to an anonymous callback function expecting a non-null value without TypeScript throwing errors? I've tried wrapping the function call in an if statement to check for null at the cal ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

Angular seed appears to experience a hiccup when the "Loading..." screen persists after the incorporation of a router-outlet

When working on a new Angular seed application using ng new, I encountered an issue where the application would get stuck at "Loading..." after adding the following to app.component.html: <router-outlet></router-outlet> In an attempt to resol ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor https://i.sstatic.net/1BrRq.png https://i.sstatic.net/3lOVD.png It can be observ ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Can you provide guidance on defining functions using standard syntax and incorporating children in React with TypeScript?

There are multiple ways to type it, such as using the interface React.FC<YourInterface> or explicitly declaring in an interface the type of children as JSX.Element or React.Node. Currently, my approach is: const MyComponent: React.FC<MyInterface& ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Adding and removing/hiding tab-panels in Angular 4 with PrimeNg: A step-by-step guide

I'm currently working on a tabView project with a list of tab-panels. However, I am struggling to find a way to dynamically hide and unhide one of the tab panels based on specific runtime conditions. Does anyone have any suggestions or insights on how ...

Comparing values between two JSON objects in Angular 8: A guide

I need to compare the values of two objects, obj1 and obj2, by ignoring keys that are missing in either object. If all key-value pairs are equal, return false; otherwise, return true. For example: If 'id' is present in obj1 but not in obj2, it s ...

Combining URLs in Angular 6 - A Step-by-Step Guide

How can I concatenate the commonUrl from CommonClass in Angular 6 for category.service.ts? common-class.ts export class CommonClass { constructor(public commonUrl : string = 'http://localhost:3000'){}; } category.service.ts import { CommonC ...