Pergunta

I'm trying to use underscore in an OO way:

var myCollection = _([]);
myCollection.push('one');
myCollection.push('two');
myCollection.push('three');

How do I get the item at a numeric index? I'm sure I'm missing something, other than using myCollection.toArray()[1]. There's no myCollection.get(1)?

Also, if I use myCollection.push('something'), it returns an array, which isn't chainable. I'm really confused why there isn't something out there like this already.

As a follow up to this question, I'm trying to use underscore in an OO way, and not have to rewrap the array/object every time. After some of these challenges, it appears its not really meant to be used this way?

So now I'm wondering, is there a better library that has a generic, chainable, OOP, collection wrapper?

Foi útil?

Solução

If you really need that method to access single elements directly on a wrapped array (or object), you can implement it yourself easily using _.mixin:

_.mixin({
    get: function(obj, key) { // works on arrays as well
         return obj[key];
    }
});

Outras dicas

If you really want to use Underscore like this, you can simply add necessary method yourself to _.prototype:

// probably name it something other then get
_.prototype.get = function(i) {
    return this.toArray()[i];
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top