2017-10-18 8 views
0

현재 맞춤 이벤트 디스패처를 만드는 중입니다.JAVASCRIPT : 사용자 지정 이벤트 디스패처에서 hasCallbackFor 함수를 만들려고합니다.

테스트 케이스 더미가 주어졌으며 hasCallbackFor (name, callback)라는 이벤트 리스너 객체에 메서드를 만드는 데 어려움이 있습니다. 내가 수집 할 수있는 것부터 hasCallbackFor 함수는 내가 만들고있는 객체의 키 이름을 가져야하고 콜백은 그 키의 배열에있는 함수입니다. 그 기능이 존재하는지 확인해야합니다. 나는이 일을하는 방법에 절대적으로 분실하고 모든 것을 시도한 것처럼 느낍니다. 이 제는, dispatchEvent 기능

/** 
* @param {string} name 
* @param {function} callback 
* @param {Object} opt_scope 
*/ 
addEventListener: function (name, callback, opt_scope) { 
    if(!EventDispatcher.myObject[name]) { 
     EventDispatcher.myObject[name] = []; 
    } 
    if(opt_scope) { 
     var bound = callback.bind(opt_scope); 
     EventDispatcher.myObject[name].push(bound); 
    } else { 
     EventDispatcher.myObject[name].push(callback); 
    } 
}, 

입니다 : 이것은 내 또는 addEventListener 기능

var shouldReturnFalseHasCallBackForIfMethodsNotAdded = function() { 
    testObj = {}; 
    var scope = { 
     executeSuccess: true 
    } 
    var testFunction = function() { 
     if (this.executeSuccess) { 
      success1 = true; 
     } 
    } 
    EventDispatcher.mixin(testObj); 
    testObj.addEventListener('test', testFunction, scope); 
    testObj.dispatchEvent('test'); 
    assert(testObj.hasCallbackFor("test", testFunction), 'should have callback registered for test event'); 
    assert(!testObj.hasCallbackFor("test", function() {}), 'should have no callback'); 
    console.log('shouldReturnFalseHasCallBackForIfMethodsNotAdded: success') 
} 

입니다 :

은 hasCallbackFor 기능에 대한 테스트 케이스입니다

/** 
* @param {string} name 
*/ 
dispatchEvent: function (name) { 
    EventDispatcher.myObject[name].forEach(function(value) { 
     value(); 
    }); 
}, 

그리고에 대한 내 hasCallbackFor 함수를 사용하려고합니다.

/** 
* @param {string} name 
* @param {function} callback 
* @return {boolean} 
*/ 
hasCallbackFor: function (name, callback) { 
    return EventDispatcher.myObject[name].includes(callback); 
}, 

이 기능은

assert(testObj.hasCallbackFor("test", testFunction), 'should have callback registered for test event'); 

줄에 테스트 케이스를 실패하고 난 공식적 이유는 아이디어가 부족했습니다. 나는 약 3 시간 동안이 코드를 봤는데 이것에 대한 통찰력을 고맙게 생각할 것이다. 고맙습니다!

답변

1

이 경우 기능 이름 testFunction은 코드 인 입니다. 돌아 가기 영업 이익

var arr = []; 
var foo = function(e){return true;}; 
arr.push(foo); 
console.log(arr.includes(foo));//true 
var bar = foo.bind('something'); 
arr.push(bar); 
arr.includes(bar);//true 
arr.includes(foo.bind('something'));//false .bind creates a new function every time 
//The worst case: 
arr.push(function(e){return true;});//anonymous function is lost forever 
console.log(arr.includes(function(e){return true;}));//false 

:
작은 예를 살펴 보자. 그래서 문제는 여기에 있습니다 : addEventListener

addEventListener: function (name, callback, opt_scope) { 
    if(!EventDispatcher.observable[name]) { 
     EventDispatcher.observable[name] = []; 
    } 
    if (opt_scope) { 
     var bound = callback.bind(opt_scope); 
     EventDispatcher.observable[name].push(bound); 
     return bound; 
    } else { 
     EventDispatcher.observable[name].push(callback); 
     return callback; 
    } 
} 

에서
반환 기능과 shouldReturnFalseHasCallBackForIfMethodsNotAdded 호출과 같이 기능에 :

var bound = callback.bind(opt_scope);//creates a new function with a new address 
EventDispatcher.myObject[name].push(bound); 

내가 두 솔루션을 제공

var foo = testObj.addEventListener('test', testFunction, scope); 
// ^^^ 
testObj.dispatchEvent('test'); 
assert(testObj.hasCallbackFor("test", foo), 'should have callback registered for test event'); 
//         ^^^ 

에 함수 바인딩scope

//addEventListener is the same as in OP 
var foo = testFunction.bind(scope); 
testObj.addEventListener('test', foo, null); 
testObj.dispatchEvent('test'); 
assert(testObj.hasCallbackFor("test", foo), 'should have callback registered for test event'); 

addEventListener에 두 작품을 보내지 마십시오.

+0

도움과 자세한 설명을 위해 정말로 감사합니다! 나는 그것이 다른 것들을 가리키는 바운드 함수와 관련이 있다는 것을 알고 그것을 해결하는 방법을 알 수 없었다. 다시 한 번 감사드립니다! – amacdonald