I have a model for my sources and a model for each segment. Each source has many segments. Each segment has an action that toggles an isSelected property.
I need to keep an updated list of selected segments. My first thought was to do something like...
App.Source = Ember.Object.extend({
selectedSourceList = Em.A(),
selectedSourcesObserver: function() {
// code to update array selectedSourceList
}.observes('segment.isSelected')
});
.. but that observes() function isn't right. I'm new to ember, so my approach may be completely wrong.
How can a method in one model observe the properties of many other models?
EDIT: corrected names to indicate that the segment model is for a single segment - not a collection of segments (that is what I plan to do in the sources model).
I think there are three parts to your question:
how to observe a collection
observers in general
managing relationships
observing a collection
The #each property helps observe properties for items in a collection: segments.#each.isSelected
observers in general
.observes() on a function is a shorthand to set up an observer function. If your goal for this function is to update a collection you might be better served by using .property() which sets up an observer and treats the function like a property:
selectedSegments: function() {
return this.get('segments').filterProperty('isSelected', true);
}.property('segments.#each.isSelected')
This means selectedSegments is the subset of segments from this object that are selected and is automatically managed as items are dropped or marked selected.
managing relationships
For plain Ember Objects you will need to manage the relationships, pushing new items into the array, etc.
segments = Em.A(), //somehow you are managing this collection, pushing segments into it
Also note the difference between Ember Objects and Ember Models. Ember Data is an optional additional library that allows specifying models and relationships and helps to manage the models for you. With Ember data you might have something like:
App.Source = DS.Model.extend({
//ember-data helps manage this relationship
// the 'segment' parameter refers to App.Segment
segments: DS.hasMany('segments'),
selectedSegments: function() {
return this.get('segments').filterProperty('isSelected', true);
}.property('segments.#each.isSelected')
});
And App.Semgent
App.Segment = DS.Model.extend({
selection: DS.belongsTo('selection')
});
Related
Here is what I am trying to understand.
Often times I find myself writing backbone like this:
var CallModel = Backbone.Model.extend({
});
var CallsCollection = Backbone.Collection.extend({
model: CallModel,
url: 'url/to/external/json'
});
It is a very basic example but as you can see, there is nothing really in the model all the data is coming into the Collection via an external url call to a json file that is build from a database.
So whats the purpose of the model? I am sure that I am probably not using backbone.js to its fullest extent which is why I am here asking you guys.
First of all, "there is nothing really in the model all the data is coming into the Collection via an external url call" - this is not true.
Let's assume you've the following:
//Model
var CallModel = Backbone.Model.extend({
defaults: {
cost:0,
duration:0
}
});
(without custom attributes or methods, there is no point in extending the original Backbone.Model)
//Collection
var CallsCollection = Backbone.Collection.extend({
model: CallModel,
url: 'url/to/external/json'
});
And the json data returned from service, probably something like:
//Response
{
callSummary: {
missed: 2,
received: 3,
totalCalls:5
totalDuration: 20
}
calls: [{
id:001,
caller:"Mr.A",
callee:"Mr.B",
cost:1,
duration:5
},{
id:002,
caller:"Mr.X",
callee:"Mrs.Y",
cost:1,
duration:7
},{
id:003,
caller:"Mr.A",
callee:"Mrs.B",
cost:1,
duration:8
}],
//and more additional information from your db
}
Now you populate your collection with data by calling it's fetch method:
CallsCollection.fetch();
Your collection should look something like:
{
models: [{
attributes: {
callSummary: {},
calls: [{},{},{}],
...
},
...
}],
length:1,
url: "url/to/external/json",
...
}
The data will be added to a model's attribute hash. If you don't specify a particular model, as Bart mentioned in his answer, backbone will populate the collection with a Backbone.Model instance: Which is still not much useful - Wew... A collection with single model having entire response data inside it's attributes as it is...
At this point, you're wondering why did I even bother creating a model, and then a collection..?
The problem here is Collections are derived from Arrays, while Models are derived from Objects. In this case, our root data structure is an Object (not an Array), so our collection tried to parse the returned data directly into a single model.
What we really want is for our collection to populate its models from the "calls" property of the service response. To address this, we simply add a parse method onto our collection:
var CallsCollection = Backbone.Collection.extend({
model: CallModel,
url: 'url/to/external/json',
parse: function(response){
/*save the rest of data to corresponding attributes here*/
return response.calls; // this will be used to populate models array
}
});
Now your collection will be something like the following:
{
models: [{
...
attributes: {
...
id:001,
caller:"Mr.A",
callee:"Mr.B",
cost:1,
duration:5
}
},{
...
attributes: {
...
id:002,
caller:"Mr.X",
callee:"Mrs.Y",
cost:1,
duration:7
}
},{
...
attributes: {
...
id:003,
caller:"Mr.A",
callee:"Mrs.B",
cost:1,
duration:8
}
}],
length:3,
url: "url/to/external/json",
...
}
This - is what we want! : Now it is very easy to handle the data: You can make use of the add, remove, find, reset and handful of other collection methods effectively.
You can pass this models array into your templating library of choice, probably with two way bindings: When the respective view for one of the call model changes, the particular model will be updated, events will propagate from your models to the collection, and the particular model will be passed into the handler functions.
You can now call fetch, save, destroy, clear and a lot of other methods with ease on single unit's of data (each model), rather than hurdle with the entire data saved in a single model - which is pretty much useless, you've to iterate through the response data manually and perform CRUD and similar operations by your own, and in most cases: re-render the entire collection view. which is very, very bad and totally unmaintainable.
To conclude: If your data source doesn't return an array of objects, or you don't parse the response and return an array of objects from which n number of models are to be populated - Then defining a collection is pretty much useless.
Hopefully, now you get the idea.
Very helpful source of info:
Backbone, The Primer: Models and Collections
Developing Backbone.js Applications
backbonejs.org
You don't need to specify a model. A Backbone collection will default to using Backbone.Model if you don't specify this option. The following would work equally well if you don't need the models of the collection to be of a particular instance.
var CallsCollection = Backbone.Collection.extend({
url: 'url/to/external/json'
});
Reference
EDIT
In essence, specifying the model option within a collection is just a way to ensure that objects added to this collection will be instances of that particular model class. If the models being added to your collection don't have any custom behaviour outside of what is available to Backbone.Model, you don't need to create and specify a model as Backbone collections will default to using an instance of Backbone.Model as I have already mentioned. If, however, you wanted to ensure that models added to a particular collection were of a particular type and shared customized behaviour (e.g. validations, defaults, etc.), you would create your own model class by extending Backbone.Model and specifying this in the collection. I hope this clears things up for you.
Sounds Weird but this is the way.
Every collection in backbone, must represent a model, so basically a collections is a list of models.
Even if your model has no data, you need to indicate it when you create a Collection.
This is how backbone works for collections.
In the data-driven paradigm of Backbone, the backbone views/routers should subscribe to model changes and act based on the model change events. Following this principle, the application's views/routers can be isolated from each other, which is great.
However, there are a lot of changes in the states of the applications that are not persisted in the models. For example, in a to-do app, there could be buttons that lets you look at tasks that are "completed", "not completed", or "all". This is an application state not persisted in the model. Note that the completion state of any task is persisted, but the current filter in the view is a transient state.
What is a good way to deal with such application state? Using a plain, non-backboned state means that the views/routers cannot listen to the changes in this state, and hence become difficult to code in the data-driven paradigm.
Your buttons filter example can be properly solved using Model events.
I suppose your buttons handlers have access to the tasks Collection. Then filter the collection and trigger events over the selected Models like:
model.trigger( "filter:selected" )
or
model.trigger( "filter:un-selected" )
The ModelView can be listening to these events on its Model and acts accordingly.
This is following your requirements of respecting the not use or "attributes that are not persistent" like selected but I don't have any trauma to use special attributes even if they shouldn't be persistent. So I also suggest to modify the selected attribute of your Models to represent volatile states.
So in your buttons handlers filter the collection and modify the selected attribute in your Models is my preferred solution:
model.set( "selected", true )
You can always override Model.toJSON() to clean up before sync or just leave this special attributes to travel to your server and being ignored there.
Comment got long so I'll produce a second answer to compare.
First, I feel like "completed", "not completed" are totally item model attributes that would be persisted. Or maybe if your items are owned by many users, each with their own "completed" "not completed" states, then the item would have a completedState submodel or something. Point being, while #fguillen produced two possible solutions for you, I also prefer to do it his second way, having models contain the attributes and the button / view doing most of the work.
To me it doesn't make sense for the model to have its own custom event for this. Sounds to me like a filter button would only have to deal with providing the appropriate views. (Which items to show) Thus, I would just make the button element call a function that runs a filter on the collection more or less directly.
event: {
'click filterBtnCompleted':'showCompleted'
},
showCompleted: function(event) {
var completedAry = this.itemCollection.filter(function(item) {
return item.get('completed');
});
// Code empties your current item views and re-renders them with just filtered models
}
I tend to tuck away these kind of convenience filter functions within the collection themselves so I can just call:
this.ItemCollection.getCompleted(); // etc.
Leaving these attributes in your model and ignoring them on your server is fine. Although again, it does sound to me like they would be attributes you want to persist.
One more thing, you said that using plain non-backboned states sacrifices events. (Grin :-) Not so! You can easily extend any object to have Backbone.Event capabilities.
var flamingo = {};
_.extend(flamingo, Backbone.Events);
Now you can have flamingo trigger and listen for events like anything else!
EDIT: to address Router > View data dealings -------------------//
What I do with my router might not be what you do, but I pass my appView into the router as an options. I have a function in appView called showView() that creates subviews. Thus my router has access to the views I'm dealing with pretty much directly.
// Router
initialize: function(options) {
this.appView = options.appView;
}
In our case, it may be the itemsView that will need to be filtered to present the completed items. Note: I also have a showView() function that manages subviews. You might just be working directly with appView in your scenario.
So when a route like /items/#completed is called, I might do something like this.
routes: {
'completed':'completed'
},
completed: {
var itemsView = ItemCollectionView.create({
'collection': // Your collection however you do it
});
this.appView.showView(itemsView);
itemsView.showCompleted(); // Calls the showCompleted() from View example way above
}
Does this help?
In this stackoverflow post i read about filtering backbone collections and using subsets.
One answer (by sled) recommends using backbone.subset.js (usage example).
I could not find any further resources on backbone.subset.js and I failed implementing it into my project.
It seems like backbone.subset.js is the perfect solution for what i'm trying to achieve.
(Having one "parent" collection that holds all models at all times, and depending on user input filtering the relevant models from the parent collection into a backbone.subset collection.)
My "parent" collection, holding all tasks:
var TasksAll = Backbone.Collection.extend({
url: '/tasks', // the REST url to retrieve collection data
model: Task // the models of which the collection consists of
});
var allTasks = new TasksAll();
Now i want to create a subset collection for e.g. tasks where task.status = 0:
var TasksTrash = new Backbone.Subset({
superset: allTasks,
filter: function(Task) {
return Task.isTrash();
}
});
var trashTasks = new TasksTrash();
Whereas inside the Task model, the method "isTrash" returns true if:
this.get('status') == 0
a) Are there any more resources on backbone.subset.js?
b) How do I implement above scenario?
c) Can I pass 'superset' and 'filter' options as params to the Backbone.Subset init function?
d) I looked into the backbone.subset.js code, when I 'reset' my parent Collection my subset Collections should be updated straight away, right?
PS: I'm fairly new to Backbone. Thanks for your help.
Looking at the source for backbone-subset, it looks as though there is a pre-initialization hook which you could utilize in order to make the 'sieve' or filter available as an option or argument:
https://github.com/masylum/Backbone.Subset/blob/master/backbone.subset.js#L50
As for providing parent as an argument, there is an outstanding patch to add that exact functionality:
https://github.com/masylum/Backbone.Subset/pull/5
With it, you can pass in parent as an option, if it is not an option the library will fall back to looking for it on the object Prototype
I am using Backbone.js to render a list of items (email recipients) that have different status, eg. confirmed, pending and so on. After the list is rendered there are options for user to filter them so the user can list all recipients, or only confirmed recipients and so on. The items (recipients) are naturally stored in a collection..
My approach is to on a filter event:
Clear all item's view's
From the app view call a filterOnStatus function in the collection that return all models and adds them to the view.
Step 2 works fine. But what's the best way to clear all items on a collection's view's.
In the Todo example application (http://documentcloud.github.com/backbone/examples/todos/index.html) they do something similar. In the app view the following code is used to clear all completed items from the list.
clearCompleted: function() {
_.each(Todos.done(), function(todo){ todo.destroy(); });
return false;
},
The difference here is that they do this by removing the actual model. And that model's view listens for the destroy event which them removes the view.
I want to keep the model.
What's the best way to solve this. Do I in the models need to stored a reference to its views and then iterate over the models and remove the views?
Is there a better approach if I want to filter on attributes in the models?
If your first step is simply clearing all items then why don't you add a simple method to your AppView that will do just that, like: clearList: function() { this.$('.list').html('') }.
Or even better, you can filter all models and render them to the temporarily element and than replace current list with it. Thus all the filtering will be done in only one DOM call (DOM is slow). Example with jQuery:
AppView.filterOnStatus = function() {
var $fragment = $('<div/>')
// filter your collection and append rendered views to $fragment
this.$('.list').html( $fragment.html() )
}
Of course there are more complicated ways, but whether you need them depends on what you're trying to achieve. From what I understood this simple approach would be fine enough.
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?
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.
This is the way I'm doing it. The collection stores a reference to the selected model, but the state is held in the model. This could then be adapted to allow more a more complex algorithm for choosing which models are selected.
JobSummary = Backbone.Model.extend({
setSelected:function() {
this.collection.setSelected(this);
}
});
JobSummaryList = Backbone.Collection.extend({
model: JobSummary,
initialize: function() {
this.selected = null;
},
setSelected: function(jobSummary) {
if (this.selected) {
this.selected.set({selected:false});
}
jobSummary.set({selected:true});
this.selected = jobSummary;
}
};
I did something like Mr Eisenhauer suggested. I wanted the concept of paged data as well. Didn't really want to mix in the selected, page number, etc into the collection itself, so I created a "model" for the table data and called it a Snapshot. Something like this:
JobSummary = Backbone.Model.extend({});
JobSummaryList = Backbone.Collection.extend({
model: JobSummary
};
JobSummarySnapshot = Backbone.Model.Extend({
defaults: {
pageNumber: 1,
totalPages: 1,
itemsPerPage: 20,
selectedItems: new JobSummaryList(), // for multiple selections
jobSummaryList: new JobSummaryList()
}
});
Check out Backbone.CollectionView, which includes support for selecting models when they are clicked out of the box. The hover case you could implement using the setSelectedModel method.
You might want to have a look at two components of mine:
Backbone.Select
Backbone.Cycle
Backbone.Select has a minimal surface area. As few methods as possible are added to your objects. The idea is that you should be able to use Backbone.Select mixins pretty much everywhere, with a near-zero risk of conflicts.
Backbone.Cycle is built on top of Backbone.Select. It adds navigation methods and a few more bells and whistles. It probably is the better choice for a greenfield project.