EzDevInfo.com

underscore

JavaScript's utility _ belt Underscore.js

Differences between lodash and underscore

Why would someone prefer either the lodash.js or underscore.js utility libary over the other?

Lodash seems to be a drop-in replacement for underscore, the latter having been around longer.

I think both are brilliant, but I do not know enough about how they work to make an educated comparison, and I would like to know more about the differences.


Source: (StackOverflow)

Using the Underscore module with Node.js

I've been learning about node.js and modules, and can't seem to get the Underscore library to work properly... it seems that the first time I use a function from Underscore, it overwrites the _ object with the result of my function call. Anyone know what's going on? For example, here is a session from the node.js REPL:

Admin-MacBook-Pro:test admin$ node
> require("./underscore-min")
{ [Function]
  _: [Circular],
  VERSION: '1.1.4',
  forEach: [Function],
  each: [Function],
  map: [Function],
  inject: [Function],
  (...more functions...)
  templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
  template: [Function] }
> _.max([1,2,3])
3
> _.max([4,5,6])
TypeError: Object 3 has no method 'max'
    at [object Context]:1:3
    at Interface.<anonymous> (repl.js:171:22)
    at Interface.emit (events.js:64:17)
    at Interface._onLine (readline.js:153:10)
    at Interface._line (readline.js:408:8)
    at Interface._ttyWrite (readline.js:585:14)
    at ReadStream.<anonymous> (readline.js:73:12)
    at ReadStream.emit (events.js:81:20)
    at ReadStream._emitKey (tty_posix.js:307:10)
    at ReadStream.onData (tty_posix.js:70:12)
> _
3

When I make Javascript files myself and import them, they seem to be working properly. Maybe there's something special with the Underscore library?


Source: (StackOverflow)

Advertisements

Sorting strings in reverse order with backbone.js

I'm trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("title");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));

The above code sorts the chapters from A -> Z, but how do I write a comparator that sorts it from Z -> A?


Source: (StackOverflow)

Underscore: sortBy() based on multiple attributes

I am trying to sort an array with objects based on multiple attributes. I.e if the first attribute is the same between two objects a second attribute should be used to comapare the two objects. For example, consider the following array:

var patients = [
             [{name: 'John', roomNumber: 1, bedNumber: 1}],
             [{name: 'Lisa', roomNumber: 1, bedNumber: 2}],
             [{name: 'Chris', roomNumber: 2, bedNumber: 1}],
             [{name: 'Omar', roomNumber: 3, bedNumber: 1}]
               ];

Sorting these by the roomNumber attribute i would use the following code:

var sortedArray = _.sortBy(patients, function(patient) {
    return patient[0].roomNumber;
});

This works fine, but how do i proceed so that 'John' and 'Lisa' will be sorted properly?


Source: (StackOverflow)

How is it possible to run multiple instances using Backbone.Paginator.js?

I am trying to use Backbone.Paginator.js to run more than one app (multiple instances of paginator) on the same page.

I created a test page. (Navigate to backbone.paginator/examples/netflix-infinite-paging).

I left the code as is for app.js and create app2.js, which is a clone of app.js but all the javascript code is located in one file and the app has been renamed to app2.

Two instances work on first load of the page but subsequent request/refreshes only load app2.js's data.

Is it possible to run multiple instances on the same page?

  • I am interested in using an auto-paging (infinite/endless scroll) so I tried to use Paul Irish's jQuery Infinite Scroll plugin but I am unable to get it to work.
  • I am initiating the plugin to run on document ready (which does not work, as expected), but also running the code in the app2's ResultView, which does not work as well.

Any ideas on how to get an auto-paging infinite scroll solution?


UPDATE: After further testing across different browsers, it seems like the problem might be to caching issue/differences. For example, in Safari, it works sometimes (randomly) when refreshing the page. I am not sure how to debug that. Any ideas?


Source: (StackOverflow)

Serialize form data to JSON [duplicate]

This question already has an answer here:

I want to do some pre-server-validation of a form in a Backbone.js model. To do this I need to get the user input from a form into usable data. I found three methods to do this:

  1. var input = $("#inputId").val();
  2. var input = $("form.login").serialize();
  3. var input = $("form.login").serializeArray();

Unfortunately, none of the provide a good reabable and developable JSON object which I require. I already looked through several questions on Stack Overflow, but I found only some extra libraries.

Doesn't Underscore.js, the current jQuery or Backbone.js provide a helper method?

I can't imagine there is no request for such a function.

HTML

<form class="login">
    <label for="_user_name">username:</label>
    <input type="text" id="_user_name" name="user[name]" value="dev.pus" />
    <label for="_user_pass">password:</label>
    <input type="password" id="_user_pass" name="user[pass]" value="1234" />
    <button type="submit">login</button>
</form>

JavaScript

var formData = $("form.login").serializeObject();
console.log(formData);

Outputs

{
    "name": "dev.pus",
    "pass": "1234"
}

Backbone.js model

var user = new User(formData);
user.save();

Source: (StackOverflow)

Use underscore inside Angular controllers

How do I use underscore library inside angularjs controllers?

On this post: AngularJS limitTo by last 2 records somebody suggested to assign an _ variable to the rootScope so that the library will be available to all the scopes within the app.

But I'm not clear where to do it. I mean should it go on the app module declaration? i.e:

var myapp = angular.module('offersApp', [])
            .config(['$rootScope', function($rootScope) { }

But then where do I load underscore lib? I just have on my index page the ng-app directive and script reference to both the angular-js and underscore libs?

index.html:

<head>
</head>
<body ng-app="offersApp">
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="scripts/vendor/angular.js"></script>
<script src="scripts/vendor/underscore.js"></script>
...  

How do I achieve this?


Source: (StackOverflow)

need explanation of the _.bindAll() function from Underscore.js

I've been learning some backbone.js and I've seen plenty of instances where _.bindAll() is used. I have read through the entire backbone.js and underscore.js documentation page to try to get a sense of what it does, but I still am very fuzzy as to what it does. Here is underscore's explanation:

_.bindAll(object, [*methodNames]) 

Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. If no methodNames are provided, all of the object's function properties will be bound to it.

var buttonView = {
  label   : 'underscore',
  onClick : function(){ alert('clicked: ' + this.label); },
  onHover : function(){ console.log('hovering: ' + this.label); }
};

_.bindAll(buttonView);

jQuery('#underscore_button').bind('click', buttonView.onClick);
=> When the button is clicked, this.label will have the correct value...

If you can help out here by giving another example perhaps or some verbal explanation, anything would be appreciated. I tried to search for more tutorials or examples, but nil turn up that serve what I needed. Most people seem to just know what it does automatically...


Source: (StackOverflow)

Why did Underscore.js remove support for AMD?

1.3.0 — Jan. 11, 2012 Removed AMD (RequireJS) support from Underscore. If you'd like to use Underscore with RequireJS, you can load it as a normal script, wrap or patch your copy, or download a forked version.

Why have they done it? Does anyone know? Because they added it only few month ago (in October), and AMD (Asynchronous Module Definition) is said to be far superior to CommonJS modules.

Update: As of December 2013, this has been supported again.


Source: (StackOverflow)

Removing duplicate objects with Underscore for Javascript

I have this kind of array:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

I'd like to filter it to have:

var bar = [ { "a" : "1" }, { "b" : "2" }];

I tried using _.uniq, but I guess because { "a" : "1" } is not equal to itself, it doesn't work. Is there any way to provide underscore uniq with an overriden equals function?


Source: (StackOverflow)

Do Underscore.js and jQuery complement each other?

I'm just starting to learn JavaScript, and stumbled over Underscore.js and jQuery. Underscore looks really cool but I wonder if jQuery does not already provide functions similar to Underscore. So, is it worthwhile to use both?


Source: (StackOverflow)

Missing Javascript ".map" file for Underscore.js when loading ASP.NET web page [duplicate]

This question already has an answer here:

I have a web page that is part of a ASP.NET web site running on Azure. It's run fine for quite a while now. Out of the blue, I am suddenly having a problem with the browser trying to download a ".map" for Underscore.js. I did some reading and apparently JQuery creates ".map" files as debugging aids for Javascript source files (".js"). However, if I look at the Scripts directory for my web site I see that this only happens for some JQuery source files and not all and I am not sure what the pattern is.

However, why would the browser be trying to load a "map" file for Underscore.js which is not part of JQuery? Also, why would this suddenly start happening? I added Underscore.js to the web page quite some time ago and never had this problem before.

The exact error I get when I look in the Chrome Debugger Console tab is:

GET http://myazureapp.cloudapp.net/Scripts/underscore-min.map 404 (Not Found) Scripts/underscore-min.map:1


Source: (StackOverflow)

Remove empty properties / falsy values from Object with Underscore.js

I have an object with several properties. I would like to remove any properties that have falsy values.

This can be achieved with compact on arrays, but what about objects?


Source: (StackOverflow)

backbone.js - handling if a user is logged in or not

Firstly, should the static page that is served for the app be the login page?

Secondly, my server side code is fine (it won't give any data that the user shouldn't be able to see). But how do I make my app know that if the user is not logged in, to go back to a login form?


Source: (StackOverflow)

Easiest way to reset Backbone's model to initial defaults?

My models already have a 'defaults' hash. When parts of the view/page are reset, I wish to reset the models back to their original defaults.

Currently I explicitly set each attribute to it's default value. Is there anything built in or javascript/underscore.js/backbone.js/jquery function that I could use to do this in a single statement?


Source: (StackOverflow)