Can you set attributes in Backbone.js collections? If so, how?

I just get into backbone.js and I thought the best way to get into it is to actually create a todo list (yes ... pretty original). Regarding humor, I searched google and docs and stackoverflow, of course, in order to add an attribute to the collection. So, in my case, the todo list is a collection of lists. However, the Todo list may have a title, as in my design, I want to be able to create multiple lists.

var TodoList = Backbone.Collection.extend({ model: ListItem }); //is this possible for collections? var newTodoList = new TodoList({name: "My first list"}); 

Many thanks for the help! Appreciate it!

+6
source share
1 answer

Yes it is possible. Look at the signature of the Collection constructor:

new collection ([models], [options])

So you can write like this:

 var ListItem = Backbone.Model.extend({}); var TodoList = Backbone.Collection.extend({ model: ListItem, initialize: function(models, options) { options || (options = {}); if (options.title) { this.title = options.title; }; } }) var iPromise = new TodoList([], { title: 'NY Resolutions' }) console.log(iPromise.title); 
+11
source

Source: https://habr.com/ru/post/918617/


All Articles