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

var currentVideos = this.get('items').pluck('video');TODO: Why does pluck not w

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");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742260847a4410875.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信