Book Image

Lo-Dash Essentials

By : Adam Boduch
Book Image

Lo-Dash Essentials

By: Adam Boduch

Overview of this book

Table of Contents (15 chapters)
Lo-Dash Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Binding contexts


You might not always want to use anonymous functions, or Lo-Dash functions, as your map() callback. This is the same case with reduce(). Luckily, you can easily bind the callback function context in both cases. For example, let's say that you have an application object that is not global. You can still make it the context of your callback function, as shown in the following code:

var app = { 
    states: [
        'running',
        'off',
        'paused'
    ],  
    machines: [
        { id: _.uniqueId(), state: 1 },
        { id: _.uniqueId(), state: 0 },
        { id: _.uniqueId(), state: 0 },
        { id: _.uniqueId(), state: 2 } 
    ]   
};  

var mapStates = _.partialRight(_.map, function(item) {
    return _.extend({
        state: this.states[item.state]
    }, _.pick(item, 'id'));
}, app);

mapStates(app.machines);
// →
// [
//   { state: "off", id: "1" },
//   { state: "running", id: " " },
//   { state: "running", id: " " },
//   { state: "paused", id: " "...