知識社群登入
Callback 應用範例 (保持泛用)
by 蘇德宙, 2012-06-06 15:28, 人氣(1764)
// just find nodes
var findNodes = function() {
  var nodes=[], found;
  while (true) {
    ...
    nodes.push(found);
  }
  return nodes;
}

// hide nodes
var hide = function(nodes) {
  var i=0, max=nodes.length;
  for ( ; i<max; i++) {
    nodes[i].style.display = "none";
  }
}


使用 callback
findNodes 的同時做 hide 來增加效率,而且保持 findNodes 的泛用性 (less coupling)
var findNodes = function(callback) {
  var nodes=[], found;
  if (typeof callback !== "function") {
    callback = false;
  }
  while (true) {
    ...
    if (callback) {
      callback(found);
    }
    nodes.push(found);
  }
  return nodes;
}

var hide = function(node) {
  node.style.display = "none";
};

findNodes(hide);  // findNodes(function(node) { node.style.display = "none"; });


物件 method 的作用域 Callback & Scope
如果 callback 是物件的方法,需要做調整 (p.67 @ JavaScript Patterns)
var app = {
  color: "green",
  paint: function(node) { node.style.color = this.color; }
}
findNodes(app.paint);  // error,因為 this 會指向全域變數,因為 findNodes 是 global
findNodes(app.paint, app);

var findNodes = function(callback, obj) {
  if (typeof callback === 'string') {  // findNodes('paint', app); 少打一個 app (app.paint)
    callback = obj[callback];
  }
  if (typeof callback === 'function') {
    callback.call(obj, found);
  }
};