backbone.js and states that are not in models - javascript

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?

Related

Backbone.sync clarification

After reading the docs, this is my understanding of sync.
I instantiate some Backbone.Model and call Collection.create(). create() eventually calls sync() and the Model is POSTed to the server. Then there is a sync in the opposite direction such that the Model on the client is given an id.
Does this update then trigger componentDidUpdate()?
Note: componentDidUpdate is a ReactJS thing, so if that doesn't make sense, the question reduces to "Is the client-side model updated and the view re-rendered?"
Since inside of my componentDidUpdate() I am making a call to save() to keep everything up to date, this subsequently makes a call to sync() which then fires a PUT request (because the Model already has an id).
I'm asking, because in my current application, creating a TodoItem seems to result in a POST and then a PUT which I find redundant. Perhaps it is for an unrelated reason.
It actually fires two POSTS and then two PUTS when adding one item, but that is another question.
The first time you save a model (one which doesn't have an id) it will make a POST, thereafter it will make a PUT (update). I think you are confusing when to use create/add/save:
Use save at any point to save the current client collection/model state to the server
Use add to add Model(s) to a collection (a single Model, an array of Models, or an array of objects which contain attributes and let the collection create them)
Use create as a shorthand for creating a model, adding it to the collection, and syncing the collection to the server.
My guess is that you are calling create and save in one operation - you should be using add and save instead, or just create.
The view will not automatically update for you, you will need to listen to changes or events on the collection/model and update the view yourself - there is no equivalent of componentDidUpdate. For example:
initialize: function() {
this.listenTo(this.collection, 'sync', this.onCollectionSync);
},
onCollectionSync: function() {
this.render();
}

Backbone state handling with nested models?

I'd like to manage all hash state attributes (#) in one Backbone model.
StateModel //Pseudo
attributes
layout : string
modelType1 : model
modelType2 : model
This way I could consistently update history entries just by serializing this single model.
HistoryController
StateModel.bind("change", this.updateHistory);
[...]
state = StateModel.toJSON()
[...]
appRouter.navigate('v1' + state, false);
How do I make the HistoryController trigger change when the nested models (in the StateController) change?
And if the hash changes - and I'd like to update my StateModel - how do these changes propagate down to the nested models? (without causing a feedback loop)
Nested models in Backbone can be tricky because the getter and setter methods do not have built-in functionality to operate at depth. However, I have found that the best way to handle this is to store Backbone models inside other Backbone models. In your example, you would instantiate StateModel and then set its modelType1 and 2 to be, say, TypeModel instances. You can then stateModel.get("modelType1").bind("change",this.updateHistory) and stateModel.get("modelType2").bind("change",this.updateHistory). Alternatively, if you are going to be creating a lot of TypeModels, you can put this binding in the initializer function.
Secondly, you can stateModel.get("modelType1").bind("change",stateModelInstance.updateFoo) or whatever method you would like to call when the modelType model changes.
The nice thing about this pattern is that if you need stateModel to change one of the modelType models you can do stateModel.set({modelType1:newModel3}) or something of that ilk. If you have set the binding action in the ininitializer of TypeModel, everything will stay synced up. If you don't want to blow out the nested model on a change, just do stateModel.get("nestedModel1").set({"foo"}:"bar"). This shouldn't cause a feedback loop unless you have bound something to your stateModel change action that changes the nested Model again but I don't know why you would do that.

Backbone.js: Best way to clear a all views

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.

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?
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.

Backbone.js with non RESTful app? (is Backbone.js right for my current project?)

I'm trying to figure out if Backbone.js is the right framework for my current project: a visualization app.
I have a number of questions:
1) State / Routing?
As this is not your typical RESTful app, but rather a visualization application with various chart types and settings for these charts, how do i maintain state in the URL?
Let's say my areaChart model has a number of defaults like this:
AreaChartModel = Backbone.Model.extend({
defaults: {
selectedCountries: [],
year: 1970,
stacked: false
},
initialize: function(){
[...]
}
});
On an update to the model I'd like to serialize some of these attributes so that I can bookmark the specific state: chartApp.html#!year=1970&stacked=false etc.
And vice-versa, when initing the app with this state, how do I "deparam" the url state and set the model? Can I use Backbone's intrinsic routing?
2) Controller and coupling?
It seems as Backbone has a pretty tight view-model coupling?
Is this really how I should bind for example my areaChartView to the model?
AreaChartView = Backbone.View.extend({
initialize: function(){
areaChartModel.bind("change:year", this.render);
}
});
Isn't this normally the role of the controller?
3) Continuation: Model vs. Controller?
Given this scenario:
A change in the "Sidebar" should trigger a sequence of functions:
1) "New data for the current selection should be loaded"
2) "Based on this data, the scales in the Visualization view should be updated"
3) "The visualization view should be rendered"
Where should I place these functions and how can I create an event in the model that I trigger when the state is stable? (i.e. when all the functions have been invoked and it's time to set the view states?)
1) I would use Backbone.js native routing as much as possible using “:params” and “*splats” , read more. You could fit all your queries into the Backbone.js routing but I would personally sacrifice certain things in favor of intuitive UI buttons
e.g. I would have the default as a line bar and you can't preset this with the URL but to change to a stacked graph would be a simple click of a button.
I would probably stray from ever using ? and & in my URL's. I might come back to this point later as it is interesting.
2) Your example is fine and you just need to remember Backbone.js MVC terminology doesn't correlate to traditional MVC.
Backbone Views are essentially the Controller in traditional MVC.
Backbone Controllers are simply a way of routing inside a framework.
The templating engine you use with Backbone.js is the traditional MVC view.
3) Still writing
Regarding question #3, I would create a Model and a View for the slider.
Then I would associate the triggering of the change event on the model to some function in the view that updates the graph's view (like changing the scales). Something like:
var Slider = Backbone.Model.extend({})
var SliderView = Backbone.View.extend({
initialize: function() {
this.model.bind('change', this.render);
}
render: function() {
// load data, change scales, etc.
}
});
var slider = new Slider();
var slider_view = new SliderView({ model: slider });
Maybe a good idea would be to put the bindings in a parent view, that would then dispatch to sub-views, coordinating their work.
Do sit down for a while and consider if maintaining the entire state is at all a good idea ? The key motivations for having url-based state management is being able to support browser based navigation buttons and being able to bookmark a page. In a visualization app, your data would probably change every moment. This is not something you want to persist in your app-url. Do you really want that when a user bookmarks your app and comes back to it three days later - he sees the visualization for three days old data ? For your scenario, assuming I have not misunderstood your requirements, I would recommend to keep the data state in your model itself.
Also regarding synchronization of views with model data, Yes you can code all the binding logic on your own. In that case your View class will take care of setting up the bindings on the first render. And upon subsequent calls to render, which can be invoked in response to any change event in the model, will refresh the DOM/canvas where the visualization is present.
Probably you should be look forward to a plugin for data-synchronization that takes care of much of boilerplate for you. This page lists some of the data-binding extensions available. Orchestrator is another solution that I have been working on, which might be helpful in this regard.

Categories

Resources