Home » Javascript » Callback seems an object instead of a function

Callback seems an object instead of a function

Posted by: admin November 1, 2017 Leave a comment

Questions:

I got really confused about callbacks. I want to use a library called node-jet and found every page on callback that callback is a function.

https://github.com/lipp/node-jet/blob/master/doc/peer.markdown

But here situation seems a little bit different and cant understand what is is. It seem callback is an object/variable instead of a function.

state.on('set', cb)

Registers a set event handler. Should be called before the state is actually added (peer.add(state)). The cb callback gets the new requested value passed in.

The function is free to:

  • return nothing, a State change is posted automatically with the newValue

  • throw an Error, the Error should be a String or an Object with code and message

  • return on Object with the supported fields:
    value: {Any, Optional} the “real/adjusted” new value. This is posted as the new value.
    dontNotify: {Boolean, Optional} Don’t auto-send a change Notification

john.on('set', function(newValue) {
  var prev = this.value();
  if (newValue.age < prev.age){
    throw 'invalid age';
  }
  return {
    value: {
      age: newValue.age,
      name: newValue.name || prev.name
    }
  };
});

In an example using same library

// create a new todo state and store ref.

 var todoState = new jet.State('todo/#' + todo.id, todo)
 todoState.on('set', function (requestedTodo) {
  todo.merge(requestedTodo)
  return {
    value: todo
  }
})
todoStates[todo.id] = todoState
peer.add(todoState)
Answers: