function writeCode(callback) {

    // do something...

    callback();

    // ...

}

function introduceBugs() {

    // ... make bugs

}

writeCode(introduceBugs); 

A Callback Example

// refactored findNodes() to accept a callback

var findNodes = function (callback) {

    var i = 100000,

          nodes = [],

          found;

    // check if callback is callable

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

        callback = false;

    }

    while (i) {

        i -= 1;

        // complex logic here...

        // now callback:

        if (callback) {

            callback(found);

        }

        nodes.push(found);

    }

    return nodes;

};

Callbacks and Scope

var myapp = {};

myapp.color = "green";

myapp.paint = function (node) {

    node.style.color = this.color;

};

The function findNodes() does something like this:

var findNodes = function (callback) {

    // ...

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

         callback(found);

    }

    // ...

};

If you call findNodes(myapp.paint), it won’t work as expected, because this.color will not be defined. The object this will refer to the global object, because findNodes() is a global function. If  findNodes() were a  method  of  an  object  called  dom (like dom.findNodes()), then this inside of the callback would refer to dom instead of the expected myapp.

pass the callback function and in addition pass the object this callback belongs to

findNodes(myapp.paint, myapp);

var findNodes = function (callback, callback_obj) {

    //...

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

        callback.call(callback_obj, found);

    }

    // ...

};

pass the method as a string

findNodes("paint", myapp);

var findNodes = function (callback, callback_obj) {

    if (typeof callback === "string") {

        callback = callback_obj[callback];

    }

    //...

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

        callback.call(callback_obj, found);

    }

    // ...

};

Asynchronous Event Listeners

document.addEventListener("click", console.log, false);

Timeouts

var thePlotThickens = function () {

    console.log('500ms later...');

};

setTimeout(thePlotThickens, 500);

Callbacks in Libraries

Focus on core functionality and provide “hooks” in the form of callbacks, which will allow the library methods to be easily built upon, extended, and customized.

JavaScript Patterns 4.2 Callback Pattern的更多相关文章

  1. JavaScript Patterns 5.5 Sandbox Pattern

    Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...

  2. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  3. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  4. JavaScript Patterns 5.1 Namespace Pattern

    global namespace object // global object var MYAPP = {}; // constructors MYAPP.Parent = function() { ...

  5. JavaScript Patterns 2.6 switch Pattern

    Principle • Aligning each case with switch(an exception to the curly braces indentation rule). • Ind ...

  6. JavaScript:回调模式(Callback Pattern) (转载)

    JavaScript:回调模式(Callback Pattern) 函数就是对象,所以他们可以作为一个参数传递给其它函数: 当你将introduceBugs()作为一个参数传递给writeCode() ...

  7. JavaScript Patterns 4.8 Function Properties - A Memoization Pattern

    Gets a length property containing the number of arguments the function expects: function func(a, b, ...

  8. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  9. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

随机推荐

  1. IP地址查询API的C#实现

    一切从登录记录开始 看到TX的登录记录之后,突然想去在登录环节也加上这个功能,然后就写了下面的具体实现代码.现在一点也不纠结IP在数据库中保存类型是UNSIGNED INT还是VARCHAR了. 干货 ...

  2. PHP如何将进程作为守护进程

    看了这篇:http://blog.codinglabs.org/articles/write-daemon-with-php.html 对里面的posix_setsid()不解 文档解释是" ...

  3. angularJs自定义服务

    在AngularJS中,系统内置的服务都是以$开头,所以我们的自定义服务尽量避免以$开头.自定义服务的方式有如下几种: 使用Module的provider方法 使用Module的factory方法 使 ...

  4. LeetCode - 42. Trapping Rain Water

    42. Trapping Rain Water Problem's Link ------------------------------------------------------------- ...

  5. Python OOP(1):从基础开始

    本文旨在Python复习和总结: 1.如何创建类和实例? # 创建类 class ClassName(object): """docstring for ClassNam ...

  6. 关于c#的一些笔记

     序: 在vs中,可以生成三种项目: 第一种:控制台项目:用于练习C#语法 第二种:桌面程序项目:比如我们经常看到的桌面程序(CS). 第三种:web项目:用于开发网站 1.我们先来说一下.net和C ...

  7. 操作AppConfig.xml中AppSettings对应值字符串

    //查询AppSettings的key         public static List sql()         {             List list = new List();   ...

  8. PUT 还是 POST ?

    http://www.oschina.net/translate/put-or-post http://my.oschina.net/u/1263964/blog/268932 这两个方法咋一看都可以 ...

  9. AC自动机基础知识讲解

    AC自动机 转载自:小白 还可参考:飘过的小牛 1.KMP算法: a. 传统字符串的匹配和KMP: 对于字符串S = ”abcabcabdabba”,T = ”abcabd”,如果用T去匹配S下划线部 ...

  10. ahjesus mongodb指定到数据盘连接不上的解决方案

    关于配置路径指定到数据盘会出现连接不上的情况 我发现是因为数据盘权限不足引起的,目前没找到治本的方法 有个治标的方法就是设置数据盘的权限和用户 sudo chmod 777 * -R  /path/d ...