0

This is very similar to another question I have active, but may as well ask it as its different and may be found useful by a different audience.

I have a custom rule for knockout validation:

ko.validation.rules["sameAs"] = {
    validator: function (val, otherObservable) {
        return val === otherObservable();
    },
    message: "Value should be same as {0}, but differs"
};

Now in raw javascript this worked fine as the usage would look like:

function SomeObject() {
   this.Email = ko.observable().extend({ required: true, email: true });
   this.ConfirmationEmail = ko.observable().extend({ required: true, email: true, sameAs: this.Email });
}

However now in Typescript land if I try to write this:

class SomeObject {
   public Email = ko.observable().extend({ required: true, email: true });
   public ConfirmationEmail = ko.observable().extend({ required: true, email: true, sameAs: this.Email });
}

I now get the error:

Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls

Which makes sense, however I am not sure how I can do what I would originally have done, unless I try to hack it into the constructor or something, which makes my classes now look a bit ghastly.

Grofit
  • 17,693
  • 24
  • 96
  • 176

1 Answers1

2

I cannot find any disadvantage of writing:

class SomeObject {
    public Email = ko.observable();
    public ConfirmationEmail = ko.observable();

    constructor() {
        this.Email.extend({ required: true, email: true });
        this.ConfirmationEmail.extend({ required: true, email: true, sameAs: this.Email })
    }
}

except of 2 additional lines of code.

In my opinion the code readability is a bit better, you dont have to read the whole long line to see what type of variable it is. Doing this separation you can show better what is going on in your code. Maybe its an aesthetic thing, but i find mixing variable declaration with 'extend' expression sometimes hard to read, especially when 'extend' is quite err... extended :) .

Slawek
  • 2,592
  • 1
  • 24
  • 26
  • Like you say its a personal preference, I prefer to just see everything associated with that variable in one place rather than having to look around elsewhere, also I prefer my PO*O objects to not have constructors as they have no logic, but like you say this solves the problem. – Grofit Mar 28 '13 at 13:48