1

I have two classes that I want to define relationships for. I am trying to use static variables to achieve this however the references to the classes are not defined.

import BaseQuery from "../../src/BaseQuery";
import Checklist from "./Checklist";

export default class Task extends BaseQuery {
  static belongsTo = [Checklist];
}

import BaseQuery from "../../src/BaseQuery";
import Task from "./Task";

export default class Checklist extends BaseQuery {
  static hasMany = [Task];
}

In the Task class, checklist is undefined and in the Checklist class Task is defined but not as I would expect it. Is there anyway to get this to work?

4

2 回答 2

3

You just experienced circular dependency. Task needs Checklist and Checklist needs Task; the interpretor cannot deal with that.

One of the soluce would be to use the get operator, which will delay the resolution of Checklist and Task classes and fix the circular dependency issue.

Checklist and Task gotta be resolved by the interpretor when calling belongsTo/hasMany.


Working example :

class Task {
  static get belongsTo() {
    return [Checklist];
  }

  static get name() {
    return 'Task-class';
  }
}

class Checklist {
  static get hasMany() {
    return [Task];
  }

  static get name() {
    return 'Checklist-task';
  }
}

console.log(Checklist.hasMany.map(x => x.name));

console.log(Task.belongsTo.map(x => x.name));

于 2018-06-12T07:12:13.113 回答
0

I don't know if you can do it from inside the class (as whichever you define first wouldn't know about the second, and it would also probably require static constructors). However, I was able to get it to work with static methods called after the classes themselves are defined:

class Rubyish{
    static appendProp(propName, value){
        if (!this[propName]) {
            this[propName] = []
        }
        this[propName].push(value)
    }
    static belongsTo(cls){
        this.appendProp('belongsToClasses', cls)
    }
    static hasMany(cls){
        this.appendProp('hasManyClasses', cls)
    }
}

class Task extends Rubyish{
}

class Checklist extends Rubyish{
}

Task.belongsTo(Checklist)
Checklist.hasMany(Task)

Edit to add: This may have been overkill, as you could do it without static methods:

class NewTask{}
class NewCheckList{}

NewTask.belongsTo = [NewCheckList]

NewCheckList.hasMany = [NewTask]
于 2018-06-12T08:13:19.470 回答