0

モデルをテンプレートに送信します。モデルにはコレクションがあります。テンプレートでは、いくつかの変数と関数をエコーし​​ます。

console.log(comments);
console.log(_.size(comments));
console.log(comments instanceof App.Collections.Comments);
console.log(_.pluck(comments, 'created'));
_.each(comments, function(com) {
    console.log(com);
});

最初の3つは機能しますが、最後の2つのアンダースコア関数は機能しません。Pluckは3xを未定義にし、それぞれは反復しません。

Object { length=3, models=[3], _byId={...}, more...}
3
true
[undefined, undefined, undefined]

アンダースコア関数を機能させるにはどうすればよいですか?

4

2 に答える 2

1

You'll want to call pluck directly on the collection, as the Collection class supports it:

http://documentcloud.github.com/backbone/#Collection-pluck

So instead of:

_.pluck(comments, 'created')

You chould call:

comments.pluck('created');
于 2012-04-04T08:25:38.980 に答える
1

Backbone collections have some Underscore methods mixed in so you can use the Underscore methods directly on the collection instance:

console.log(comments.pluck('created'));
comments.each(function(com) { console.log(com) });

Demo: http://jsfiddle.net/ambiguous/3jRNX/

This one:

console.log(_.size(comments));

works fine for you because _.size looks like this:

_.size = function(obj) {
  return _.toArray(obj).length;
};

and _.toArray calls the collection's toArray:

// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
  if (!iterable)                return [];
  if (iterable.toArray)         return iterable.toArray();
  if (_.isArray(iterable))      return slice.call(iterable);
  if (_.isArguments(iterable))  return slice.call(iterable);
  return _.values(iterable);
};

which unwraps the collection's data to give you the correct length. The above is taken from the 1.3.1 source, the current Github master version's _.size has a different implementation so your _.size call is likely to break during an upgrade.

于 2012-04-04T08:33:38.847 に答える