7

I'm working my way through "Learning jQuery" (Third Edition).

In Chapter 4: "Manipulating the DOM" there is a section explaining something called the "Value Callback". This is a new one for me.

The author explains this via an example of list of links wherein the ID's of each must be unique.

From the book:

"A value callback is simply a function that is supplied instead of the value for an argument. This function is then invoked once per element in the matched set. Whatever data is returned from the function is used as the new value for the attribute. For example, we can use this technique to generate a different id value for each element, as follows:"

Chaffer, Jonathan (2011-09-23). Learning jQuery, Third Edition (p. 116). Packt Publishing. Kindle Edition.

jQuery(document).ready(function($){

// get all external links
   $('div.chapter a').attr({
        rel:'external',
        title:'Learn more at Wikipedia',
        id: function ( index, oldValue ) {
                return 'wikilink-' + index;
        }
    });
})

Works like a charm, but the mechanics of the id: property escape me.

  1. How does parameter 1 (index) know to be an integer?
  2. How does the function know to increment index?
  3. How does the second parameter (oldValue) know to hold the old value of the property (before modification)?
  4. Is this a jQuery construct? A JSON thing? It's cool. it works, but ...what the heck is this "value callback" thing made of?

Please advise

Community
  • 1
  • 1
sleeper
  • 3,446
  • 7
  • 33
  • 50

2 Answers2

6

1) How does parameter 1 (index) know to be an integer?

jQuery passes an integer.

2) How does the function know to increment index?

The callback doesn't increment index, the jQuery method does.

3) How does the second parameter (oldValue) know to hold the old value of the property (before modification)?

jQuery passes it.

The answers to questions 1-3 are perhaps best understood by a function that performs something similar to $.attr:

Array.prototype.each = function (f) {
    var i;
    for (i=0; i < this.length; ++i) {
        f(i, this[i]);
    }
};

['zero', 'one', 'two'].each(function (i,item) {console.log({i: item})});

f is a callback. each is responsible for iterating over a collection and calling f for each index & item. The same code structure can be used for functions:

/* Map each item in a sequence to something else, 
 * returning a new sequence of the new values.
 */
Array.prototype.map = function (f) {
    var i, result = [];
    for (i=0; i < this.length; ++i) {
        result[i] = f(i, this[i]);
    }
    return result;
};

['zero', 'one', 'two'].map(function(i,item) {return item.length});
// result: [4, 3, 3]

/* Return a sequence of the items from this sequence 
 * for which 'keep' returns true.
 */
Array.prototype.filter = function (keep) {
    var i, result = [];
    for (i=0; i < this.length; ++i) {
        if (keep(i, this[i])) {
            result.push(this[i]);
        }
    }
    return result;
};

['zero', 'one', 'two'].filter(function(i,item) {return item.length <= 3});
// result: ['one', 'two']

Implementation of mapconcat, foldl and foldr left as an exercise. As another exercise, rewrite map and filter in terms of each.

Note these functions are merely intended to illustrate how callbacks work. They may cause problems in production code.

4) Is this a jQuery construct? A JSON thing? It's cool. it works, but ...what the heck is this "value callback" thing made of?

Callbacks are a generic technique that jQuery makes extensive use of. They're the key feature of functional programming, where functions are data that can be operated on just like other data types. Thus, you have functions that take functions as arguments and can return functions. In certain contexts, callbacks are also known as "continuations" and form the basis of continuation passing style (CPS). This is particularly important for asynchronous function calls [2] (where the function returns before the computation completes, as opposed to synchronous calls), such as is used for Ajax requests. To see some of the power of CPS, read "Use continuations to develop complex Web applications".

The other aspect of this, the "value" in "value callback", is that, as JS is a dynamically typed language (types are associated with data, rather than variables), formal parameters can be bound to objects of any type. A function can then behave differently depending on what is passed. Sometimes this is implemented by examining the type of the argument, which is in effect ad-hoc polymorphism (the function, rather than the language, must handle dispatch). However, parametric polymorphism or (failing that) duck typing should always be preferred over examining argument types. Parametric polymorphism is achieved by ensuring that all types that can be passed to a given function support the same interface (method names, arguments, preconditions, postconditions & so on). For example, all sequence types should have a length property and be indexed by integers; as long as that holds, you can use your own sequence type with many functions that take arrays.

I'm not sure what you mean by JSON, but it's probably not what is generally meant. JSON is a data interchange format based on a limited version of the JS object literal syntax. JSON is not involved anywhere in the sample code or quoted text.

Community
  • 1
  • 1
outis
  • 75,655
  • 22
  • 151
  • 221
  • Even better breakdown! I "get it" now. So this pattern is NOT an example of currying at all? – sleeper Jul 03 '12 at 02:55
  • This discussion of currying is still so new 2 me, it's over my head. However, your breakdown COMPLETELY answers and explains the issues raised in my question. So I've switched my choice of answers to yours. Thanks for all the work you put into this answer! – sleeper Jul 03 '12 at 03:04
4

It's a JQuery construct. If you look at the source, you will find that JQuery is inspecting the parameter in order to learn whether you passed a value or a function. If it's a function, it handles as you see.

outis
  • 75,655
  • 22
  • 151
  • 221
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Wow. Very Cool. Can you recommend further reading on this topic? – sleeper Jul 03 '12 at 00:24
  • Actually, `$.attr` doesn't make use of currying. Currying is converting an *n*-ary function (a function that takes *n* arguments) into *n* unary functions, each of which (excepting the last) returns a unary function. – outis Jul 03 '12 at 00:34