Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make one model 'selected' in a Backbone.js collection?

I have a collection of models in my Backbone.js application.

It's a list of items that you can hover over with the mouse or navigate around with the keyboard.

If the mouse is hovering, or if the keyboard navigation has the item selected they will both do the same thing: set that particular item/model to be 'selected'.

So in my model, I have an attribute basically called

selected: false 

When it's hovered over, or selected with the keyboard, this will then be

selected: true 

But, what is the best way to ensure that when this one model is true, the others are all false?

I'm current doing a basic thing of cycling through each model in the collection and then set the selected model to be true. But I wonder if there is a better, more efficient way of doing this?

like image 987
littlejim84 Avatar asked Jun 29 '11 11:06

littlejim84


People also ask

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.

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 the only method available in the backbone JS history?

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


1 Answers

Being selected seems a responsibility outside of a model's scope. The notion of selected implies that there are others, but a model can only worry about itself. As such, I'd consider moving this responsibility elsewhere where the notion of many models and having one selected seems more natural and expected.

So consider placing this responsibility either on the collection as an association. So, this.selected would point to the selected model. And then you can add a method to return the selected model in a collection.

Alternatively, you could give this responsibility to the view. You might do this if the selectedness of a model is purely a concern in the View layer.

The by-product of removing the responsibility from the model is that you eliminate the need to cycle through the entire collection when a new model becomes selected.

like image 135
Bill Eisenhauer Avatar answered Oct 17 '22 07:10

Bill Eisenhauer