最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Underscore pluck not working on array of models? - Stack Overflow

programmeradmin5浏览0评论
var currentVideos = this.get('items').pluck('video');

//  TODO: Why does pluck not work here?
var currentVideosDurations = _.map(currentVideos, function (currentVideo) {
    return currentVideo.get('duration');
});

var test = _.pluck(currentVideos, 'duration');
console.log("Test:", test);

I was wondering why my second pluck doesn't work, but my map works fine? I thought these were equivilant usages.

Here's a screenshot of a console log showing this.get('items') and the array of currentVideos.

var currentVideos = this.get('items').pluck('video');

//  TODO: Why does pluck not work here?
var currentVideosDurations = _.map(currentVideos, function (currentVideo) {
    return currentVideo.get('duration');
});

var test = _.pluck(currentVideos, 'duration');
console.log("Test:", test);

I was wondering why my second pluck doesn't work, but my map works fine? I thought these were equivilant usages.

Here's a screenshot of a console log showing this.get('items') and the array of currentVideos.

Share edited Aug 14, 2013 at 17:17 Sean Anderson asked Aug 14, 2013 at 16:56 Sean AndersonSean Anderson 29.4k33 gold badges132 silver badges242 bronze badges 2
  • 1 Can you also post a list of sample collection for this problem – Sushanth -- Commented Aug 14, 2013 at 17:02
  • Yeah one moment. I've uploaded a screenshot. – Sean Anderson Commented Aug 14, 2013 at 17:14
Add a ment  | 

2 Answers 2

Reset to default 7

The backbone model object doesn't store the properties you get from the model at the top level javascript object. The currentVideo backbone model object actually stores the attributes deeper within the javascript object, in (currentVideo.attributes).

_.pluck(currentVideos, 'duration') checks for the top level attribute (e.g. currentVideo['duration']), which doesn't exist.

The distinction is that Backbone Model objects are more sophisticated than basic javascript objects and don't get attributes by just retrieving object['attrName'].

I thought these were equivilant usages.

Nope. pluck is accessing properties with that name, but get is a method invocation. However, to shorten the map you can use invoke:

var currentVideosDurations = _.invoke(currentVideos, "get", "duration");
发布评论

评论列表(0)

  1. 暂无评论