In the application we are developing, we have a CollectionView whose every ItemView contains a link to the item-details page. Also, every ItemView contains a checkbox, because items can be selected in the CollectionView to perform bulk actions on them.
When switching to the ItemDetails view, we want to keep the state of the CollectionView, ideally without having to redraw it (a bit like GMail when switching from inbox to mail and back). Our solution is to render the two views in two different regions and to hide one when switching from one to the other.
My perplexity about this solution is that
Marionette doesn't seem to be meant for this kind of use.
It is not very memory-friendly, since all the DOM elements are never deleted.
Is there any better solution to achieve this goal?
Storing the state somewhere, close the CollectionView and redraw it later is another possible solution, but would it imply a heavy computation overhead? (we are quite scared about redrawing views).
Marionette allows for showing a view in a region without closing the view that was already rendered. You simply pass in {preventClose: true} to the show() method of the region. You would still need to maintain a reference to the collection view though so you can later re-show it or close it yourself.
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.region.md#showing-a-view
Unless your collection is very large, there's not a problem with just rerendering the collectionView when switching back from a itemDetail view. You do need to store the state of the checkboxes indeed.
However, I don't see what's really wrong with your other approach. It's probably even faster and there's nothing wrong with just hiding one region and showing another. If that works for you, go ahead.
Regarding the memory issue, as long as you're looking at the collection or itemDetail there isn't much to gain by closing either one of the views (especially if your itemDetail views are not very large). Once you move away from that section (thus not looking at the collection or itemDetail view anymore) you could just close the layout that contains these two regions. That'll free up any memory used by these regions.
Related
I have a view containing of many sub-views, which have relatively heavy CSS properties. and I need to add them(about 10-30 depending on screen-width) to browser every time user changes the sort or the category.
In android we handle this heavy task of adding many views, by using the ListView which basically does the heavy lifting once and then reuses the view later on.
I wanted to know if there is anyway in javascript to cache the view so appending them to the parent would be a lot faster.
in my performance tests, it takes about 500ms to just append the view to the parent DOM. but if there is a way to reuse a cached DOM to make things faster, it would be a lot better.
thanks in advance
I assume that in your case, one sub-view is needed at one time.
So, this library might inspire you http://nexts.github.io/Clusterize.js/
The idea is keep your whole data model in window object and render part of it (associated with sub-view) when user sort or category.
I have a parent view with a nested view in the middle.
On a state change, the nested view seems to stick for a second or two before loading the next state. It's as though the nested view is lagging behind or something.
For example, after logging in, the login form is still visible for a second or two in the middle of the page after the state change. The parent view changes instantly, but that nested view just seems to stick.
I've been pretty careful about items on the watch list, and use one-time binding wherever possible.
But I really don't think it has to do with that, because this happens even early on in the application (from login to the main page), and other than this issue, application performance is fine.
I've googled a lot about this, but haven't turned up anything useful.
Any ideas on what to check or how to debug this?
You say it only happens the first time you transition after loading the app. So it could be you are injecting a service into the child view that you are using the first time in your app. This service is taking some time to instanciante. Servises are singletons, so this lag is only visible the first time.
Look at the answer in this thread for a possible solution, somebody had the exact some problem:
How to instantiate a service dynamically?.
Another solution might me to inject that service into the parent view as well, so you get the lag while loading the app not on first transition.
I'm thinking about the optimal way to structure my Backbone application. The problem is that I have various complex states, each made by some views showing while all the others are hidden.
What is the canonical way to handle this in Backbone? Two things that I've thought are either controlling the state by the router (calling views hide / show methods) or making the views listen for route event.
The problem with the first method is that the router must be aware of all the views existing in the application.
The problem with this second solution is that I have to make all the views listen to all the events and hide for any of them but a couple that make them show.
Thanks for pointing me to a lean solution.
I use a FSM machine to change the state of the application. Each states shows and hides the appropriate view. My views use transition to animate in and out, so changing the state is more complex, then simple show/hide - it animates in and out from one state into another. I have forked https://github.com/fschaefer/Stately.js to fit my needs.
I can share my personal experience with such a problem. I don't know if it's the best solution, but it worked for me.
My problem was even worse because I had several routers and each of them should hide/show views that belong to it. The solution I chose was similar to the first option you consider.
In my router there is an array which holds all existing views. When the state changes and route callback executes all other views are hidden with this simple code view[i].hide() and the proper one is shown. You can make View model and Views collection if you would like to have more control.
I think it's a better solution, because when you add a new route, you don't have to add route events to all views. Moreover, your views stay decoupled from the router, they may even don't know it exists.
I have a backbone.js app, whose views have multiple states, which differ substantially from each other ("View","Edit", etc). There are at least 2 different templates for every view. This is OK. My problem is with the JS view managing code.
I rely on an initalize-thin-render-thick approach (which, I think is pretty bad), where the render method is where 80%-90% of the logic occurs. When I want to change the state, I simply call the render method with a specific parameter ("view","edit"). On the basis of that, the view decides what to show and what not, to which events to bind, etc.
I think this is bad, because, on one side it puts bottlenecks on the rendering process, on another, it is not proper state machine, which means that I am not carrying about possible callbacks that might have been bound previously. When I receive the view, I simply clean the view and that's it.
I also observed, that I am not using the delegated event system, provided by backbone, which I think is another minus, because I think, it is very well implemented (BTW, does it make sure to unbind callbacks, when a certain DOM element is removed?)
I think I need some serious refactoring. Please, help with some advice, as to what the best approach for a multi-state Backone view would be.
What I tend to do for these cases is to make a toplevel view that manages a subview for each individual state (index, show, edit, etc.). When a user action is invoked, e.g. "edit this user", "delete this user", "save my changes", the active state view signals the router (directly, or through a hyperlink), and the router will tell the toplevel view to update its state.
Continuing the user editor example, let's say that I have a top level view called UserEditorView. It renders a basic container for the user editor (title bars, etc.) and then, by default, instantiates and renders Users.IndexView inside that container.
Users.IndexView renders the list of users. Next to each user is an edit icon, which is a link to "#users/555/edit". So, when the user clicks it, that event goes to the router, which tells UserEditorView, "hey, I want to edit user #555". And then UserEditorView will remove the IndexView (by calling its .remove() method), instantiate Users.EditView for the appropriate user model, and put the EditView into the container.
When the user is done editing the user, she clicks on "Save", and then EditView saves the model. Now we need to get back to the IndexView. EditView calls window.router.navigate('users', { trigger: true }), so the URL gets updated and the router gets invoked. The router then calls .showIndex() on the UserEditorView, and the UserEditorView does the swap back to IndexView from EditView.
On a simple way to manage unloading of events, I've found this article on zombie views quite useful.
Basically, I don't have a toplevel view, but I render all the views using a view handler that takes care of the views for a given container.
To make your renderer thinner, I would recommend using routes. They are easy to setup, and you can have different views for each route. Or, what I'm used to do is just to have different templates. Using a general Backbone.View overwrite:
Backbone.View = Backbone.View.extend({
initialize: function(attrs) {
attrs = attrs || {}
if(!_.isUndefined(attrs.template)) {
this.template = attrs.template;
}
}
});
I've noticed that I reuse views in two ways:
1. edit views differ only in the underlying model and template, but not the associated logic (clicking the submit validates and saves the model)
2. the same view can be reused in several places with different templates (like a list of users as a ranking or you accounts)
With the above extension, I can pass {template: '/my/current/template/} to the view, and it will be rendered as I want. Together with routes, I finally got a flexible, easy to understand and thin setup.
I'm coming across a bit of an awkward problem. I have a Web page with quite a few buttons on it that need to be disabled and enabled at various points. Now if this were a Swing (or any otehr desktop UI interface for that matter), it would be quite trivial: I would simply add listeners for the model changes I was interested in and update the UI accordingly.
This is basic MVC stuff really.
Thing is, I'm at a bit of a loss as to how to handle this nicely in Javascript. I'm going down a route that will end up with some real spaghetti code where the click listeners for the buttons are updating the UI controls and that's just not going to end well.
EDIT: Let me give you a more concreate example.
Example
Imagine a screen that lists open orders. Those orders are presented in a table as each row (order) has multiple attributes against it, such as who is currently managing the order, who made the order, what it's for, when the order was made and the status of the order.
I've done it so you can select one (or more) of these orders by clicking on the rows. This adds a "selected" class, which changes the styling, much like a list.
As to the behaviour, if a user selects one order then certain actions become available, such as Open Order (to view the details), Take Owneship, Cancel and so on. The attributes of the order may also affect what actions are available eg if the order is "owned" by somebody else already, certain actions will be disabled.
Some of these options (like opening the order) aren't available if you've selected multiple orders.
Additionally via a background Ajax call the list refreshes with new orders periodically. The user can also click refresh or can filter the orders (by name, date range and so on) and then reload the orders. While the orders are reloading certain buttons get disabled.
I was going to do a second example but I think that one is sufficiently complex to illustrate the kind of problem. Now I've started this by giving various controls classes. For example, elements with the "select" class might be disabled/enabled/styled when an item is selected.
Now this works reasonably well in simple cases but I'm running into problems where the state of a control depends on multiple conditions. Also the classes are getting fractured by things like some elements want to be styled, some controls want to be disabled/enabled and in some cases both things need to happen.
In Swing I tended to handdle this kind of thing by having a sort of updateUI() method, which would be called whenever the state of a relevant control or model was changed. It would then set the state of all the controls explicitly. Now this is arguably not the most efficient way (eg if you have 30 controls and only need to update one of them it's a bit of a waste) but I found the simplicity was worth it. The alternative was that controls/models ended up with too information about what controls they depended on or those that depended on them. It go tmessy from a coupling point of view.
But I have no such (obvious) mechanism in Javascript. Inobtrusive Javascript as advocated by jQuery is great because it stops random code snippets being littered throughout your code. But I need to go a step further nad have some way of managing the complexity of this (because it is quite a complex screen and will only get more complex).
If you want to preserve your sanity, use a state machine.
You don't really give details about what your UI does, so I'll make up an example. Let's say you have a file upload page. The user should be able to select a file, click an upload button, and then be returned to the page they came from, when uploading is complete. So you could have three states, "SelectFile", "Uploading", "Finished". In the "SelectFile" state, controls should be enabled to allow the user to select a file. In the "Uploading" state, these control should be disabled, and the user should see a progress indicator. In the "Finished" state, the user should be redirected.
Of course, it sounds like your case is more complicated, but the same ideas will apply. You may need more than one state machine, if portions of user interface interact. That's fine.
When you want to change the enabled/disabled elements on the user interface, you just change the state of the state machine. The state machine itself tells the various user interface controls to update themselves based on the current state. You can use a Bharani's (good, up voted) suggestion of using classes to do this. Or whatever mechanism works for you.
The nice thing is that the controls no longer interact with each other. They only interact with the state machine. So you get rid of all the cases where states bounce around incorrectly or endlessly recurse.
Assign specific class names to the divs. That way even if they overlap in functionality you can simply keep adding class names to the div and because of the chain nature of jquery all registered event handlers will be executed.
For controlling form elements during ajax call - you can add ajaxStart and ajaxEnd or you can use ajaxComplete and handle all your code inside the callbacks.
I think i get your problem. I have worked on such screens before and i always ended up refactoring to structure the code better. But at times it will be easier if you could re-organize the functionality itself so that you don't have to handle all things in one place. I think GUI should also be treated like a function - do one thing and one thing well.
I think data modeling is important for JavaScript apps. I am working on this scheduling project for medical clinics and I have a JSON data structure that models chairs/patients in an office. Ember updates the views (UI widgets) automatically when the business logic changes in the models. So right off the bat a lot of sphagetti code is eliminated. If you are doing something graphically intense with user interaction it is almost a crime not to use an existing MVC pattern or to create your own MVC JS classes. The structured discipline is off putting at first but when you see later how it lowers your blood pressure and makes maintenance so much more enjoyable it is worth it. I wouldn't use it for simple one-off projects if they are small. It is better for medium complexity or advanced complexity. Anything that will take me more than a week I will use Ember. I have used knockout.js and Angular and I really like Ember with its Handlebars templating syntax. Easy on the eyes and efficient.