1

I'm trying to pass this context within this chaining without any 'hacks' - I just want to use apply, call or bind (description is below):

var ArticlesCollection = Backbone.Collection.extend({
    model: ArticleModel,
    parse : function(response) {
        var dateSinceFormatter = this.dateSinceFormatter; // right now solution

        return _.chain(response)
            .map(function(response) {

                if(!_.difference(["id", "title", "link", "source", "image"], _.keys(response)).length) {
                    return {
                        id : (!response.id ? _.uniqueId() : response.id),
                        title : response.title,
                        content : response.preamble,
                        thumbnailUrl : ((!response.image) ? '' : response.image.url),
                        linkUrl: response.link,
                        timeAgo : '',
                        categoryName: '',
                        persistentUrl: response.link,
                        commentsEnabled: false
                    };
                } else {
                    return {
                        id : response.id,
                        title : response.title,
                        content : response.preamble,
                        thumbnailUrl : response.thumbnail.url,
                        linkUrl: response.url,
                        timeAgo : dateSinceFormatter(response.published.datetime, response.published.niceformat), // I want to use this.dateSinceFormatter
                        categoryName: response.mainCategory,
                        persistentUrl: response.persistentUrl,
                        commentsEnabled: response.hasComments
                    };
                }
            })
            .value();
    }
});

any thoughts?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Oskar Szura
  • 2,469
  • 5
  • 32
  • 42

2 Answers2

2

Next to the obvious .bind() solution, Underscore's map (just as the native one) does offer a third parameter for the this context of the callback:

response.map(function(res) { … }, this)
// or
_.map(response, function(res) { … }, this)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You can pass the context as an argument to most of Underscore functions. For example, you would call

_.chain(response)
    .map(function(response) {...}, this)
    .value()

And a demo http://jsfiddle.net/nikoshr/MH9Qh/1/

nikoshr
  • 32,926
  • 33
  • 91
  • 105