How to call cleanup code in Angular on browser refresh - javascript

I have a server API which holds session state in the form of managed objects. Unfortunately, there is no way to get references to those managed objects apart from when they are created.
This means there is a need to destroy the objects when the web application is finished with them (otherwise they accumulate on the server and eventually I hit a limit where no more can be created). I have this cleanup code in controller destroy event handlers, but they don't seem to be called when the user, say, refreshes the browser.
What's a proper Angular-ish way to call cleanup code on refresh or close? Is there such a pattern or should the server API be refined to provide a way to get such references? Unfortunately, I'm not in a position to be able to change the server API easily.

Related

How can you tell when Meteor minimongo has been synchronized with the mongo server

I have a Meteor application and I want be able to check on the client side when all the changes made by the client to a published Collection have been written to the server.
I've looked at minimongo and the code in the ddp-server, but I don't see any straightforward way to tell when the changes have been successfully written to the server.
Minimongo outline the process for saving data:
User triggers an interaction on the client
The simulation applies some mutations to the state locally
The RPC is fired to be executed on the server
After some time, the RPC returns with the result
After some more time, RPC returns an "updated" message (on DDP level), meaning that all the changes from RPC have persisted
At this point we know, that all the actual changes from the server are synced, we can throw away the simulated mutations (preserving the real changes from the server)
I can override LocalCollection.prototype.saveOriginals and LocalCollection.prototype.retrieveOriginals to know when they are each called, but I'm not sure how to verify when the data is actually saved. retrieveOriginals is getting called even when the Meteor server is down.
Is there any other place to hook a callback in or listen for an event to know when changes are synched?
If you're looking to implement custom observation, perhaps this might help :
Establishes a live query that invokes callbacks when the result of the query changes. The callbacks receive the entire contents of the document that was affected, as well as its old contents, if applicable. If you only need to receive the fields that changed, see observeChanges.
http://docs.meteor.com/#/full/observe or http://docs.meteor.com/#/full/observe_changes
In addition you're probably looking to use Mongo's writeConcern with Meteor, that I'm not sure how, but hope the tip helps; https://docs.mongodb.org/v3.0/reference/method/db.collection.save/

When to call the backend and when to store locally (angularjs)

I have an ionic app and a Parse.com backend. My users can perform CRUD functions on exercise programmes, changing every aspect of the programme including adding, deleting, editing the exercises within it.
I am confused about when to save, when to call the server and how much data can be held in services / $rootScope?
Typical user flow is as below:
Create Programme and Client (Create both on server and store data in $localStorage).
User goes to edit screen where they can perform CRUD functions on all exercises within the programme. Currently I perform a server call on each function so it is synced to the backed.
The user may go back and select a different programme - downloading the data and storing it localStorage again.
My question is how can I ensure that my users data is always saved to the server and offer them a responsive fast user experience.
Would it be normal to have a timeout function that triggers a save periodically? On a mobile the amount of calls to the server is quite painful over a poor connection.
Any ideas on full local / remote sync with Ionic and Parse.com would be welcome.
From my experience, the best way to think of this is as follows:
localStorage is essentially a cache layer, which if up to date is great because it can reduce network calls. However it is limited to the current session, and should be treated as volatile storage.
Your server is your source of truth, and as such, should always be updated.
What this means is, for reads, localstorage is great, you don't need to fetch your data a million times if it hasn't changed. For writes, always trust your server for long term storage.
The pattern I suggest is, on load, fetch any relevant data and save it to local storage. Any further reads should come from local storage. Edits, should go directly to the server, and on success, you can write those changes to localstorage. This way, if you have an error on save, the user can be informed, and/or you can use localstorage as a queue to continue trying to post the data to the server until a full success.
This is called "offline sync" or sometimes "4 ways data binding". The point is to cache data locally and sync it with a remote backend. This is a very common need, but the solutions are unfornately not that common... The ideal flow would follows this philosophy:
save data locally
try to sync it with server (performing auto merges)
And
Periodically sync, along with a timer and maybe some "connection resumed" event
This is very hard to achieve manually. If been searching modules for a long time, and the only ones that come to my mind don't realy fit your needs (become they often are backend providers that give you frontend connectors; and you already have an opiniated backend), but here they are anyway:
Strongloop's Loopback.io
Meteor
PouchDB

Javascript/Python/d3JS: refresh html page when underlying JSON changes

I'm controlling a d3JS interface from another platform. The workflow: Data->Python to create JSON->d3JS to generate graphic->load the html page locally in a browser.
Is anyone aware of a way within this workflow to force a page reload when the JSON data is updated?
This is essentially a problem of how to push updates from the server to the client.
There are two approaches:
Fake it. You could use AJAX polling to periodically ask the server whether new data is available.
Do it for real. You could use WebSockets to push the data from the server to the client when an update occurs.
With the new data in hand, it should be simple to bind in D3 via the General Update Pattern. See http://bl.ocks.org/mbostock/3808218
If you must reload the page, you can also use either of these approaches to trigger it.

How to update asynchron pages upon event from other client?

I'm currently fooling around with AJAX. Right now, I created a Markdown previewer that updates on change of a textarea. (I guess you know that from somewhere... ;-) ).
Now, I'm trying to figure out, how to update a page upon an event is fired from another client. So to say an asynchron message board. A user writes something, an event is called, the post is written.
But on the other clients' pages, the new post is of course not yet available until they reload and get the updated list of posts from the database.
Now, how can you get this to work asynchronously? So in that moment when one client does something, the other clients all get to know that he did something?
I don't think this can be done completely in AJAX, but I also have no idea whatsoever how to implement this on server-side, as it would require a page reload to inform the other clients of the event.
I'm thinking of creating a file or database entry that hashes the current state of data. Whenever a client loads the page, he saves this hash. Then, a timer (does this exist in JavaScript?) checks for the hash every few seconds.
As soon as anyone changes the databse, the hash is recalculated. If the script sees that the hash was changed and is different to the one saved, it reloads the contents form the database and saves the new hash.
Is that even going to work?
Polling that is light as possible is really the best solution here. Even if you did use a socket or something... That's still basically a live connection waiting around that will likely have to poll itself (albeit in a more effecient way).
20 queries in 10 minutes that have responses like {"updates":false} shouldn't even be putting a dent in your application. I mean imagine someone browsing your site requesting 20 pages and the related images/scripts/etc (even if some caching is involved), there could easily be hundreds of requests requiring all sorts of wasted database queries to information to be displayed on the page they don't actually care about.
You could use polling. For example each client might be sending continuous AJAX requests to the server say each 30 seconds to see if new posts are available and if yes, show them:
setInterval(function() {
// TODO: Send an AJAX request here to the server and fetch new posts.
// if new posts are available update the DOM
}, 30 * 1000);
On the other hand when someone decides to write a new post you send an AJAX (or not AJAX) request to the server to store this post in the database.
Another less commonly used approach is the concept of Comet and the HTML 5 WebSockets implementation which allow the clients to be notified by the server of changes using push.

how to update a Django page without a page reload?

My Django app displays data from a database. This data changes without user intervention, i.e. behind the scenes. Whenever it changes, I would like the webpage to update the changed sections without a full page reload.
Obviously AJAX springs to mind. When the page is loaded initially (or manually, fully re-loaded later on), the rendered template loads a JavaScript that runs window.onload = update("all"), update(...) in turn triggers a number of XMLHTTPRequests which again return data that gets transformed into HTML pieces for the corresponding sections. All works fine. At the initial page load.
Now I find myself in a Python function that saves a new object to the database.
How do I tell the browser to run update(...) ?
Do I need to somehow manually issue a request to a url that is mapped to a view which in turn renders a template that contains the JavaScript code to run update(...) ??? Oh my!
I feel like I'm not following the usual approaches.
Maybe I'm just standing to close in front of the problem.
Can anyone help me ?
2021 update: Use channels: https://channels.readthedocs.io/en/latest/
You have two choices
Have the browser poll using setTimeout()
Look into Comet -- this is a technique for pushing data from the server to the browser.
Here's an article on Comet in Django
two approaches:
just update the database and wait until the next AJAX query. That means it should do the query periodically, you'll have to balance between immediacy and server load. It helps a little if you can do a cheap query to just verify if there has been an update. Maybe make that check rely only on memcached instead of going to the DB
use comet. In short: the client does an AJAX query asking for the update. the server sees there's no update, so it doesn't answer. Instead, the connection is kept open for a long time. Eventually either the update comes and the server finally answers, or the client times out and kill the connection. In that case, the client should immediately reissue the query to keep waiting for the update.
You can also use The Websocket API https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Categories