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. ASP.NET Core学习零散记录

    赶着潮流听着歌,学着.net玩着Core 竹子学Core,目前主要看老A(http://www.cnblogs.com/artech/)和tom大叔的博客(http://www.cnblogs.com ...

  2. c++容器(vector、list、deque)

    vector ,deque 和 list 顺序性容器: 向量 vector :   是一个线性顺序结构.相当于数组,但其大小可以不预先指定,并且自动扩展.它可以像数组一样被操作,由于它的特性我们完全可 ...

  3. C# Form实现自定义光标

    WinForm代码如下: using System; using System.Reflection; using System.Runtime.InteropServices; using Syst ...

  4. php配合jquery实现增删操作

    后台使用php,前台引用jquery,实现增删操作,代码如下: <script type="text/javascript" src="http://keleyi. ...

  5. Access数据库的常用数据类型和alter的用法

    一.Access比较常用的数据类型:文本.备注.数字.日期/时间.货币 意思          Sql                    Access 1)文本      nvarchar(30) ...

  6. ASP.NET AJAX Control Toolkit

    https://ajaxcontroltoolkit.codeplex.com/ 警告 7 未能找到引用的组件“Antlr3.Runtime”. 警告 6 未能找到引用的组件“HtmlAgilityP ...

  7. [PHP] 自动加载的实现

    基于psr的规范,使用命名空间和spl_autoload_register()来实现自动加载 文件结构: |--Api |--Account.php |--User.php|--Service |-- ...

  8. Ubuntu配置任意版本的apt-get镜像

    我们知道,迄今为止,Ubuntu已有多个发行版,如11.04.11.10,以至于现在最新的16.*.而我们平常通过apt-get来安装软件,如果OS版本不同,那么镜像源的配置就不同,否则就会出现找不到 ...

  9. lnmp+phpmyadmin配置与出现问题

    本博客归moka同学(新浪微博:moka同学)本人亲自整理,如有使用,请加链接注明出处. lnmp 安装完全后,配置phpmyadmin .其访问方式为 http://202.18.400.379/p ...

  10. centos下完全卸载mysql

    版权声明:本文为博主原创文章,未经博主允许不得转载. yum方式安装的MySQL 1.yum remove mysql mysql-server mysql-libs compat-mysql51 2 ...