JavaScript로 커스텀 콜백 만들기 my callback

현재 함수 실행이 끝나면 콜백 함수를 실행하기 만하면됩니다.

function LoadData() 
{
    alert('The data has been loaded');
    //Call my callback with parameters. For example,
    //callback(loadedData , currentObject);
}

이 기능의 소비자는 다음과 같아야합니다.

object.LoadData(success);

function success(loadedData , currentObject) 
{
  //Todo: some action here 
}

이것을 어떻게 구현합니까?



답변

실제로 코드는 거의 작동합니다. 콜백을 인수로 선언하면 인수 이름을 사용하여 직접 호출 할 수 있습니다.

기본

function doSomething(callback) {
    // ...

    // Call the callback
    callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
    // I'm the callback
    alert(a + " " + b + " " + c);
}

doSomething(foo);

이 호출은 doSomething이고, 호출 foo하면 “건물이 여기로 간다”는 경고를 보냅니다.

함수를 호출하고 결과 ( )를 전달하는 대신 함수 참조 ( foo) 를 전달하는 것이 매우 중요합니다 foo(). 귀하의 질문에, 당신은 그것을 올바르게 수행하지만 일반적인 오류이기 때문에 지적 할 가치가 있습니다.

더 고급스러운 것들

때로는 콜백을 호출하여에 대한 특정 값을 볼 수도 this있습니다. JavaScript call함수 를 사용하면 쉽게 할 수 있습니다 .

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.call(this);
}

function foo() {
    alert(this.name);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Joe" via `foo`

인수를 전달할 수도 있습니다.

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
    // Call our callback, but using our own instance as the context
    callback.call(this, salutation);
}

function foo(salutation) {
    alert(salutation + " " + this.name);
}

var t = new Thing('Joe');
t.doSomething(foo, 'Hi');  // Alerts "Hi Joe" via `foo`

때로는 콜백을 제공하려는 인수를 개별적이 아닌 배열로 전달하는 것이 유용합니다. 당신은 그렇게 할 수 있습니다 apply:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.apply(this, ['Hi', 3, 2, 1]);
}

function foo(salutation, three, two, one) {
    alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Hi Joe - 3 2 1" via `foo`


답변

콜백을 실행하기 전에 콜백이 실제 함수인지 확인하는 것이 좋습니다.

if (callback && typeof(callback) === "function") {

  callback();
}


답변

내 2 센트 동일하지만 다른 …

<script>
    dosomething("blaha", function(){
        alert("Yay just like jQuery callbacks!");
    });


    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function")
        callback();
    }
</script>


답변

function loadData(callback) {

    //execute other requirement

    if(callback && typeof callback == "function"){
        callback();
   }
}

loadData(function(){

   //execute callback

});


답변

   function callback(e){
      return e;
   }
    var MyClass = {
       method: function(args, callback){
          console.log(args);
          if(typeof callback == "function")
          callback();
       }
    }

================================================

MyClass.method("hello",function(){
    console.log("world !");
});

================================================

결과는 다음과 같습니다

hello world !


답변

무언가가 완료되었을 때 함수를 실행하려는 경우. 좋은 해결책 중 하나는 이벤트를 듣는 것입니다. 예를 들어, 난을 구현하는거야 Dispatcher하는 DispatcherEvent다음 ES6와 클래스를 :

let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)

const loadSuccessCallback = (data) =>{
   ...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')

디스패처 :

class Dispatcher{
  constructor(){
    this.events = {}
  }

  dispatch(eventName, data){
    const event = this.events[eventName]
    if(event){
      event.fire(data)
    }
  }

  //start listen event
  on(eventName, callback){
    let event = this.events[eventName]
    if(!event){
      event = new DispatcherEvent(eventName)
      this.events[eventName] = event
    }
    event.registerCallback(callback)
  }

  //stop listen event
  off(eventName, callback){
    const event = this.events[eventName]
    if(event){
      delete this.events[eventName]
    }
  }
}

디스패처 이벤트 :

class DispatcherEvent{
  constructor(eventName){
    this.eventName = eventName
    this.callbacks = []
  }

  registerCallback(callback){
    this.callbacks.push(callback)
  }

  fire(data){
    this.callbacks.forEach((callback=>{
      callback(data)
    }))
  }
}

행복한 코딩!

추신 : 내 코드가 누락되어 일부 오류 예외를 처리합니다.


답변

function LoadData(callback)
{
    alert('the data have been loaded');
    callback(loadedData, currentObject);
}