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. php动态获取函数参数

    PHP 在用户自定义函数中支持可变数量的参数列表.其实很简单,只需使用 func_num_args() , func_get_arg() ,和 func_get_args()  函数即可. 可变参数并 ...

  2. .Net魔法堂:发个带附件的邮件

    一.前言   由于工作需要最近把邮件发送封装成WebService,现在把代码记录在此,以便日后查阅. 二.二话不说写代码 private void _SendMail(string form, st ...

  3. 重构第19天 提取工厂类(Extract Factory Class)

    理解:本文中的“提取工厂类”是指如果要创建的对象很多,则代码会变的很复杂.一种很好的方法就是提取工厂类. 详解:一般来说我们需要在代码中设置一些对象,以便获得它们的状态,从而使用对象,所谓的设置通常来 ...

  4. Winform开发框架之客户关系管理系统(CRM)的报价单和销售单的处理

    在前面介绍了很多CRM相关的界面和实现思路的随笔文章,本篇继续介绍一下系统中用到的一些经验和技巧片段.本篇随笔主要介绍客户关系管理系统(CRM)的报价单和销售单的处理界面效果,使用列表内置的选择代替弹 ...

  5. Mysql主从备份和SQL语句的备份

    MySQL服务器的主从配置,本来是一件很简单的事情,无奈不是从零开始,总是在别人已经安装好的mysql服务器之上 ,这就会牵扯到,mysql的版本,启动文件,等一些问题. http://www.cnb ...

  6. ASP.NET使用UpdatePanel实现AJAX

    ScriptManager和UpdatePanel控件联合使用可以实现页面异步局部更新的效果.其中的UpdatePanel就是设置页面中异 步局部更新区域,它必须依赖于ScriptManager存在, ...

  7. js定时器调用参数的方法

    var userName="Tony"; //根据用户名显示欢迎信息 function ss(_name){ alert("ss,"+_name); } 使用字 ...

  8. 重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedFilesVector VirtualizedItemsVector 绑定

    [源码下载] 重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedF ...

  9. Studio for ASP.NET Wijmo:使用 C1Pager 对 DataList 控件分页

    Studio for ASP.NET Wijmo 控件值得称赞的一点是它不仅仅单独为 C1 控件而开发.还可以配合其他控件使用,也正体现了C1控件为提高开发人员工作效率而设计的宗旨.简单的举一个例子, ...

  10. ex_KMP--Theme Section

    题目网址: http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110060#problem/B Description It's time f ...