私は、ほとんど要求を管理しないクラスがあります。したがって、リクエストはコレクションとして設定されます。私はこの方法で長いswitch/if else文を書く必要がなくなりました。Javascript Map()の "value"としてfunction/classを使用することの意義
// Manager class
class makeManagerRequests() {
private list = [];
private createList(body) {
this.list.push(body)
}
createEmployee(body) {
this.createlist(body);
}
updateManager(body);
deleteManager(body);
}
// Employee class
class makeEmployeeRequests() {
private list = [];
private createList(body) {
this.list.push(body)
}
createEmployee(body) {
this.createlist(body);
}
updateEmployee(body)
deleteEmployee(body)
}
// Usage in a generic widget
class makeRequests() {
requestMap = new Map();
constructor(makeManagerRequests, makeEmployeeRequests) {
}
createRequestMap() {
requestMap.set('createManager', this.makeManagerRequest.createManager.bind(this));
requestMap.set('updateManager', this.makeManagerRequest.updateManager.bind(this));
requestMap.set('deleteManager', this.makeManagerRequest.deleteManager.bind(this));
requestMap.set('createEmployee', this.makeManagerRequest.createEmployee.bind(this));
requestMap.set('updateEmployee', this.makeManagerRequest.updateEmployee.bind(this));
requestMap.set('deleteEmployee', this.makeManagerRequest.deleteEmployee.bind(this));
}
makeRequest(data) {
let req = requestMap.get(data.requestType);
req(data.body)
}
}
これ自体は機能します。
「サービス」から「ウィジェット」へのマップを使用するとcreatelist()
が定義されなくなるようにキーワード「this」の変更範囲が見つかった。しかし、私はバインドせずにこれを行うだけで動作します。
// I can test this with mocking the makeManagerRequest
makeRequest(data) {
this.makeManagerRequest.updateEmployee(body)
}
私は.bind(this)
が必要です。なぜ "これ"の変化がわからないのですか?この問題は、私がサービスをテストし模擬しようとしているときに発生します。私はスパイが呼び出されたことはありません。だから私はバインドマップを作成するときに新しい機能を作成すると思います。だから私はスパイできません
spyOn(MockMakeManagerRequest, 'updateEmployee')
私はどのように関数自体がMap()に格納されているかを調べようとしています。私はこのコレクションに技術的な意味合いを探しています。この作業をどのようにして行うことができるので、私はこれを中心にテストを実装できます。
これは実際に角度2アプリで使用されています。しかし、私はMap()の値として格納されたときに何が起こるか/テスト関数をテストしようとしているので、大きな違いはないと思う。
少なくとも関連する:http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback、http://stackoverflow.com/質問/ 3127429/how-does-the-this-keyword-work、おそらく私はこれらのうちの1つ(おそらく2番目の)を重複した投票で使うべきでした。 –
ええ、本当に、もしあなたが 'Map'の面を見ていれば、それはその2番目のものの複製です。しかし、有用な場合に備えて、私は以下のコミュニティwikiの回答を残しておきます。 –