Backbone.js is a JavaScript framework that provides the structure of web applications by separating the application’s data (models) from its presentation (views) and its logic (controllers). It is designed for minimal and flexible, and it works well with other libraries and frameworks, such as Underscore.js and jQuery.
In this article, we are going to discuss Underscore Methods in Backbone.js. Underscore.js is a JavaScript library that provides a wide range of utility functions for working with arrays and objects. Backbone.js, is a JavaScript library for building web applications with a structured architecture, includes a subset of the Underscore.js library.
Syntax:
_.method(data, function);
Where the method is the underscore method being invoked (e.g. each, map, reduce, etc.), data is the data collection (array or object) on which the method is being applied, and function is the function that defines the operation to be performed on the data collection.
Parameters: The parameters for underscore methods in Backbone.js vary depending on the method being used.
For example, the callback function for _.each takes three arguments (element, index, list), and the callback function for _.map takes three arguments (element, index, list) and it should return the new value for that element. The callback function for _.reduce takes four arguments (memo, element, index, list) and it should return the reduced value.
Additionally, some underscore methods may also require additional parameters. For example, _.sortBy takes an additional parameter iterator, which is a function that returns the sorting criteria, _.find and _.filter take a predicate parameter, which is a function that defines the true test to be applied to the elements in the collection.
Methods: Some of the most commonly used underscore methods in Backbone.js include:
- _.each(list, iterator): Goes through each element in a list and performs a function on it.
- _.map(list, iterator): Creates a new list by applying a function to each element in an original list.
- _.reduce(list, iterator, memo): Combines all elements in a list into a single value.
- _.find(list, predicate): Finds the first element in a list that matches a certain condition.
- _.filter(list, predicate): Creates a new list with all elements that match a certain condition.
- _.where(list, properties): Creates a new list with all elements that have certain properties.
- _.reject(list, predicate): Creates a new list with all elements that do not match a certain condition.
- _.every(list, [predicate]): Returns true if all elements in a list match a certain condition.
- _.some(list, [predicate]): Returns true if at least one element in a list matches a certain condition.
- _.pluck(list, propertyName): Extracts a specific property from each element in a list.
- _.sortBy(list, iterator): Sorts a copy of a list based on the result of applying a function to each element.
- _.isEqual(a, b): Compares if two objects have the same value.
Example 1:
HTML
<!DOCTYPE html> < html > < head > < script src = </ script > < script src = </ script > < style > h1 { color: green; text-align: center; } h3 { text-align: center; } </ style > </ head > < body > < h1 >GeeksForGeeks</ h1 > < h3 >< u >Underscore Methods in Backbone.js</ u ></ h3 > < script type = "text/javascript" > // Create a collection of books var books = [{ title: "The Great Gatsby", author: "F. Scott Fitzgerald" }, { title: "To Kill a Mockingbird", author: "Harper Lee" }, { title: "Pride and Prejudice", author: "Jane Austen" }, { title: "The Catcher in the Rye", author: "J.D. Salinger" }]; // Use the map method to create // an array of book titles var bookTitles = _.map(books, function (book) { return book.title; }); document.write("< b >Book Titles: </ b >", bookTitles); document.write("< br >< br >"); // Use the findWhere method to find // a book by its title var gatsby = _.findWhere(books, { title: "The Great Gatsby" }); document.write("< b >The Great Gatsby: </ b >", JSON.stringify(gatsby)); document.write("< br >< br >"); // Use the reject method to find books that // are not written by J.D. Salinger var notSalinger = _.reject(books, function (book) { return book.author === "J.D. Salinger"; }); document.write("< b >Books not written by J.D. Salinger: </ b >", JSON.stringify(notSalinger)); document.write("< br >< br >"); var sortedBooks = _.sortBy(books, "title"); document.write("< b >Books sorted by title: </ b >", JSON.stringify(sortedBooks)); </ script > </ body > </ html > |
Output:
Explanation: At the top of the script, an array of books is created with various properties such as title and author. The script then uses the underscore library to perform different operations on this array of books.
The first operation is the use of the map method, which creates an array of book titles by iterating through the books array and returning the title property of each book. The resulting array of book titles is then displayed on the page using the document.write() method.
Next, the findWhere method is used to find a specific book by its title, in this case, “The Great Gatsby”. The result is displayed on the page in the form of a JSON object.
The reject method is then used to find books that are not written by a specific author, in this case, J.D. Salinger. The result is displayed on the page in the form of a JSON object.
Finally, the sortBy method is used to sort the books array by the title property. The result is displayed on the page in the form of a JSON object.
Example 2:
HTML
<!DOCTYPE html> < html > < head > < script src = </ script > < script src = </ script > < style > h1 { color: green; text-align: center; } h3 { text-align: center; } </ style > </ head > < body > < h1 >GeeksForGeeks</ h1 > < h3 >< u >Underscore Methods in Backbone.js </ u ></ h3 > < script > // Define a model for a Person var Person = Backbone.Model.extend({}); // Define a collection of Person models var PeopleCollection = Backbone.Collection.extend({ model: Person }); // Create a collection of Person models var people = new PeopleCollection([{ name: "John Doe", age: 30 }, { name: "Jane Smith", age: 25 }, {}, { name: "Henry Smith", age: 45 }, {}, { name: "Jamie Keith", age: 63 }, { name: "Bob Johnson", age: 35 }]); var age1 = parseInt(prompt("Enter Age")); // Use underscore's filter method to // create a new collection of Person // models where age is greater than 30 var olderPeople = _.filter(people.models, function (person) { return person.get("age") > age1; }); document.write("People older than " + age1 + " are:\n"); document.write("< br >< br >"); // Output the names of the older people _.each(olderPeople, function (person) { document.write(person.get("name")); document.write("< br >"); }); </ script > </ body > </ html > |
Output:
Explanation: The script uses the filter method from the Underscore library to filter the models in the PeopleCollection that have an age greater than the age entered by the user.
Then it uses each method to iterate over the filtered collection and write the names of the older people to the document.
Reference: https://backbonejs.org/#Model-Underscore-Methods