Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you set attributes on Backbone.js Collections? If so, how?

Tags:

backbone.js

I am just getting into backbone.js and I thought the best way to get into it is to actually build a todo list (yea...pretty original). Humor aside, I have searched google and the docs and stackoverflow of course, for a way to add an attribute to a collection. So, in my case a todo list is a collection of listitems. However a Todo List can have a title as according to 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"}); 

Thanks a lot for the help! Appreciate it!

like image 236
Charles Avatar asked Jun 21 '12 00:06

Charles


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is collections in Backbone JS?

Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.

Which method can be used to manipulate the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.


1 Answers

Yes, it's possible. Look at the signature of the Collection constructor:

new Collection([models], [options])

So you could 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);
like image 135
theotheo Avatar answered Dec 31 '22 20:12

theotheo