Pass object and function to javascript class and return onSuccess and onError

I try to define a javascript class that will receive an object as a parameter and some self define callback functions like onSucess and onError and use those functions to return a response to the user.

Here is what I have tried so far

class User {

    constructor(param) {
        this.param = param;
    }

    static create(param) {
        return new User(param);
    }

    onSuccess() {

    }

    onError() {

    }

    showForm() {

    }
}

And this is how I want to invoke the class

let user = User.create({
    name: 'name_here', 
    email: '[email protected]',
    age: 37,
    onSuccess: (response) => {

    },
    onError: (error) => {

    }
})
user.showForm()

My question now is how can I invoke a User class like this

let user = User.create({
    name: 'name_here', 
    email: '[email protected]',
    age: 37,
    onSuccess: (response) => {

    },
    onError: (error) => {

    }
})
user.showForm()

Though that may not be the proper way to define the class and its functions, but that how I want the class to be called.

I will appreciate any corrections or suggestions.

Thanks.

Imagine the class is like this:

class User {
    constructor(param) {
        Object.assign(this, param);
    }

    static create(param) {
        return new User(param);
    }

}

and I want to invoke the User class like this:

let user = User.create({
    name: 'name_here',
    email: '[email protected]',
    age: 37,
    onSuccess: (response) => {
        alert("onSuccess");
    },
    onError: (error) => {
        alert("error");
    }
})

Upvotes: 2

Views: 464

Answers (1)

Rasheed
Rasheed

Reputation: 21

Pass the onSuccess, and onError in the params as callback like so:

class User {
  constructor(param) {
    this.param = param;
  }

  static create({onSuccess, onError, ...param}) {
      try {
        const newUser = new User(param);
        onSuccess(newUser);
      } catch (e) {
          onError(e)
      }
  }

  showForm() {}
}

let user = User.create({
    name: 'name_here', 
    email: '[email protected]',
    age: 37,
    onSuccess: (response) => {
      console.log("Success!");
    },
    onError: (error) => {
      console.log("Error!");
    }
})

Upvotes: 2

Related Questions