SIGN IN SIGN UP

A modern JavaScript utility library delivering modularity, performance, & extras.

0 0 82 JavaScript
2016-07-24 09:52:04 -07:00
define(['./_baseRest', './_createWrap', './_getHolder', './_replaceHolders'], function(baseRest, createWrap, getHolder, replaceHolders) {
2015-01-08 00:37:01 -08:00
2016-07-24 09:52:04 -07:00
/** Used to compose bitmasks for function metadata. */
2016-11-13 22:49:46 -08:00
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_PARTIAL_FLAG = 32;
2015-01-08 00:37:01 -08:00
/**
2016-04-01 23:28:48 -07:00
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
2015-01-08 00:37:01 -08:00
*
* This method differs from `_.bind` by allowing bound functions to reference
2016-03-26 00:00:01 -07:00
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
2015-01-08 00:37:01 -08:00
* 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 _
2016-03-26 00:00:01 -07:00
* @since 0.10.0
2015-01-08 00:37:01 -08:00
* @category Function
2015-12-16 17:53:20 -08:00
* @param {Object} object The object to invoke the method on.
2015-01-08 00:37:01 -08:00
* @param {string} key The key of the method.
2015-12-16 17:49:07 -08:00
* @param {...*} [partials] The arguments to be partially applied.
2015-01-08 00:37:01 -08:00
* @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!'
*
2016-02-01 23:13:04 -08:00
* // Bound with placeholders.
2015-01-08 00:37:01 -08:00
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
2016-07-24 09:52:04 -07:00
var bindKey = baseRest(function(object, key, partials) {
2016-11-13 22:49:46 -08:00
var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
2015-12-16 17:49:07 -08:00
if (partials.length) {
2016-05-07 11:49:46 -07:00
var holders = replaceHolders(partials, getHolder(bindKey));
2016-11-13 22:49:46 -08:00
bitmask |= WRAP_PARTIAL_FLAG;
2015-01-08 00:37:01 -08:00
}
2016-07-24 09:52:04 -07:00
return createWrap(key, bitmask, object, partials, holders);
2015-12-16 17:49:07 -08:00
});
2015-01-08 00:37:01 -08:00
2016-02-07 23:04:40 -08:00
// Assign default placeholders.
bindKey.placeholder = {};
2015-01-08 00:37:01 -08:00
return bindKey;
});