Search code examples
backbone.jscoffeescriptunderscore.jsbackbone-layout-manager

Underscore.js "some" not return boolean


I'm using underscore.js to check if an element is true within a list. Here is the coffeescript code for it:

uploading  = _(@getViews ".file-forms").some (view) ->
    view.uploading is true

printing 'uploading', instead of returning true or false, gives:

uploading
  y
   _chain: true
   _wrapped: false
   __proto__: Object

Here is the definition of 'some' for underscore: http://underscorejs.org/#some.

In addition, getViews is a function from backbone layoutmanager defined here: https://github.com/tbranyen/backbone.layoutmanager/wiki/Nested-views

Here is the output of other variables that might make this easier to debug:

_(this.getViews(".file-forms"))
 y
  _chain: true
  _wrapped: Array[1]
  0: d
  length: 1
  __proto__: Array[0]
  __proto__: Object

_
 function (a){if(a instanceof y)return a;if(this instanceof y)this._wrapped=a;else return new y(a)}

Solution

  • If you have a look at getViews, you'll see what's going on:

    getViews: function(fn) {
      //...
      if (typeof fn === "string") {
        return _.chain([this.views[fn]]).flatten();
      }
      //...
    }
    

    If you look at all the possible return values, you'll see that they're all the result of _.chain calls without a _.value call to peel off the chaining wrapper. That means that getViews is returning a chainable Underscore wrapper, not the simple array you're expecting.

    You shouldn't be doing _(@getViews '...') since the getViews return value is already wrapped in Underscore. You should be able to do something like this instead:

    uploading = @getViews(".file-forms").some((view) -> view.uploading is true).value()
    

    As an aside, I'm a little suspicious of your v.uploading is true test; explicit checks against true and false can cause odd behavior (especially in CoffeeScript where is is really ===). I'd probably use (v) -> v.uploading as the function instead. Of course, this is personal preference.