This repository was archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbindKey.js
67 lines (62 loc) · 2.1 KB
/
bindKey.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
define(['../internal/baseSlice', '../internal/createWrapper', '../internal/replaceHolders'], function(baseSlice, createWrapper, replaceHolders) {
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
PARTIAL_FLAG = 32;
/**
* Creates a function that invokes the method at `object[key]` and prepends
* any additional `_.bindKey` arguments to those provided to the bound function.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist.
* See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @category Function
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [args] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // using placeholders
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
function bindKey(object, key) {
var bitmask = BIND_FLAG | BIND_KEY_FLAG;
if (arguments.length > 2) {
var partials = baseSlice(arguments, 2),
holders = replaceHolders(partials, bindKey.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(key, bitmask, object, partials, holders);
}
// Assign default placeholders.
bindKey.placeholder = {};
return bindKey;
});