I am writing an application using python and flask.
In the webinterface, the user is able to make small customized programs using blockly.
Some of the already existing blocks have a dropdown menu.
All that works fine.
But now I want to have a block with a dropdown menu where the options are certain files on a usb stick the python backend found by walking through the usb stick directory.
I would like to fill the dropdown menu with these files now. I cannot, however, know them in advance and that is why they have to be dynamically generated - but by python, not by javascript or that like.
I already found this here: https://developers.google.com/blockly/guides/create-custom-blocks/dropdown-menus (at "Dynamic menu" at the end), but that does not help in my case, since I want the information to come from the python backend and not from javascript.
Does anyone know a way to do this?
Thank you a lot in advance!
This is a pretty old question, so I'm not sure if the OP still needs an answer, but I'm answering on the assumption that this is a situation where the OP is using an asynchronous JavaScript call to the backend and can't just return the results because of that.
We have a not dissimilar situation in our application (albeit using a nodejs backend) where we're populating dropdowns based on options retrieved from Google Cloud Datastore. We have a React App, so our solution was to have a Flux store attached to the window which our asynchronous call populates upon completing, and then have the dropdown generation code access that store. Obviously, a full Flux store may not be appropriate for all situations, but my general advice here would be to pass in an option generator function and have it read from a store or other variable on the window, and then have your call to the backend run on page load (or when otherwise appropriate) and populate the store on the window. If your app inits before the call is done, you can have it set up to show that it's loading options based on a flag on the store.
As a very simplified case, you might have:
// on page load
window.store = {done: false};
myBackendCall()
.then(function(results){
window.store = {
results: results,
done: true
};
})
.catch(function(error){
console.error(error);
window.store = {results: [], done: true};
});
Then in your selector, you might go with something like:
function generateOptions(){
if(!window.store.done) {
return [['Loading...', 'loading']];
} else {
return [['Select a file', '']].concat(window.store.results);
}
}
this.appendDummyInput()
.appendField(new Blockly.FieldDropdown(generateOptions), fieldName);
Obviously, this is a gross simplification, but I think it's enough to show the technique. We actually made our own custom Blockly fields for this for other reasons, but this should still work with a vanilla Blockly dropdown. Swap out Promise chaining for callbacks if that's how your setup is. You could also make the call inside the block and set a variable on the block itself (this.store or whatever), but that would result in multiple calls being made for multiple instances of the block, so that may not be appropriate for you.
Related
I have the classic problem everyone has: I did something, change the interface. Now, I have the option of murdering the code with stuff like this, which I currently have to do:
ajax_call.done(function() {
//Look at the current view, see what data came, do a check like:
if(data_that_came_back.component_activated == true) {
//Update the view with a new view that I have to write custom templates and so on. }
)
});
This is dirty. It forces me to keep thinking about classes when I should only be thinking of data and a controller should decide what view to change based on what data I get back. I know this is what React was built for, but is there no cleaner solution, a library that I can use for this specific thing?
I'm basically trying to go from this:
to this (when the user clicks "Activate"), when the AJAX call is processed:
and finally, to this, once the AJAX call is done and successful:
I can't even think what hell I'd have to go through if I had to handle more cases (such as, what if a weird error happens, what if the call is not successful, what if resources are not available, etc.).
I'm making a mobile app using Cordova and AngularJS. Currently I have installed ui-router for routing but I'm open to any other alternative for routing.
My desire: I want to cache certain views bound with parameters. In other words I want to cache paths (or pages).
Example situation: let's say that we see some dashboard page, click on some book cover which redirects to the path book/2. This path is being loaded for the first time into app. Router redirects from HomeController to BooksController (whatever the name). Now the BooksController loads data for given $stateParams (book id = 2) and creates view filled with info about chosen book.
What I want in this situation:
I go back to the dashboard page - it is already loaded (cached?)
I choose book #2 again
Controller or router notices that data about this book is already loaded
The view isn't being recreated, instead it's being fetched from cache
Actually, it would be best to cache everything what I visit based on path. Preloading would be cool too.
Reason: performance. When I open some list of books then I want it to show fast. When view is being created every time, then animation of page change looks awful (it's not smooth).
Any help would be appreciated.
EDIT:
First of all, since I believe it's a common problem for many mobile HTML app programmers, I'd like to precise some information:
I'm not looking for hacks but a clear solution if possible.
Data in the views uses AngularJS, so YES, there are things like ng-bind, ng-repeat and so on.
Caching is needed for both data and DOM elements. As far as I know, browser's layout operation is not as expensive as recreating whole DOM tree. And repaint is not what we can omit.
Having separate controllers is a natural thing. Since I could leave without it I cannot imagine how it would work anyway.
I've got some semi-solutions but I'm gonna be strict about my desire.
Solution 1.
Put all views into one file (I may do it using gulp builder) and use ng-show. That's the simplest solution and I don't believe that anyone knowing AngularJS would not think about it.
A nice trick (from #DmitriZaitsev) is to create a helper function to show/hide element based on current location path.
Advantages:
It's easy.
KIND OF preload feature.
Disadvantages:
all views have to be in a single file. Don't ask why it's not convenient.
Since it's all about mobile devices, sometimes I'd like to "clear" memory. The only way I can think of is to remove those children from DOM. Dirty but ok.
I cannot easily cache /book/2 and /book/3 at the same time. I would have to dynamically create DOM children on top of some templates for each view bound with parameters.
Solution 2.
Use Sticky States AND Future States from ui-router-extras which is awesome.
Advantages:
Separated views.
Very clear usage, very simple since it's just a plugin for ui-router.
Can create dynamic substates. So it would be possible to cache book1, book2 but I'm not sure about book/1 and book/2
Disadvantages:
Again, I'm not sure but I didn't found an example with caching a pair/tuple (view, parameters). Other than that it looks cool.
This is precisely the problem I had to solve for my site 33hotels.com. You can check it and play with the tabs "Filter" and "Filter List" (corresponding to different Routes), and see that the View is updated instantly without any delay!
How did I do it? The idea is surprisingly simple - get rid of the Router!
Why? Because the way the Router works is it re-compiles the View upon every single Route change. Yes, Angular does cache the Template but not the compiled View populated with data. Even if data do not change! As the result, when I used the Router in the past, the switch always felt sluggish and non-reactive. Every time I could notice annoying delay, it was a fraction of second but still noticeable.
Now the solution I used? Don't re-compile your Views! Keep them inside your DOM at all times! Then use ng-hide/ng-show to hide/show them depending on the routes:
<div ng-show="routeIs('/dashboard')">
<-- Your template for Dashboard -->
</div>
<div ng-show="routeIs('/book')">
<-- Your template for Book -->
</div>
Then create a function routeIs(string) inside your Controller to test if $location.path() matches string, or begins with string as I am using it. That way I still get my View for all pathes like /book/2. Here is the function I am using:
$scope.routeBegins = function () {
return _.some(arguments, function (string) {
return 0 === $location.path().indexOf(string);
});
};
So no need to be smart with caching - just keep it in the DOM. It will cache your Views for you!
And the best part is - whenever your data is changed, Angular will instantly update all the Views inside your DOM, even the hidden ones!
Why is this awesome? Because, as user, I don't have to wait for all the parsing and compiling at the moment I want to see the result. I want to click the tab and see my results immediately! Why should the site wait for me to click it and then begin all the re-compiling as I am waiting? Especially when this could be easily done before, during the time my computer is idle.
Is there any downside? The only real one I can think of is loading memory with more DOM elements. However, this actual byte size of my views is negligible, comparing e.g. with all JS, CSS and images.
Another possible but avoidable downside is the re-compilation cost of the hidden views. This is where you can get smart and avoid computation-heavy parts depending on the current routes.
Also, you are not re-compiling the whole View, just the parts affected by data changes, which also lowers computational cost.
I find it quite remarkable that everyone is using Routes and seems to be completely unaware (or ignorant) of this problem.
1) About static pages in the app (views), angular takes care of loading them.
for example: for your dashboard page you need not worry about caching the page, as angular will take care of it. Angular will only load the dashboard view once and on all next requests for the dashboard view, angular will just show you the view(not load the file for view), if it is all a static view without any data loaded by ajax calls.
2) if your dashboard is itself loading the book list(or similar data) via ajax, then you can tell your controller to only load the data once and store it to localstorage and on subsequent requests to the dashboard page can only load the data from the localStorage.
3) similar approach can be used when your BooksController loads the data into a view. You can check in your BooksController if the request for a particular book is been previously made and if not your can store it to localstorage or database. and if the data was previously requested then you can load the same data from the storage without making a request to server.
Example situation:
say user makes request for book1, then
your controller i.e BooksController check whether the same data was requested before,
if not, you can load the data via the ajax call from server and also save it to local storage.
if it was loaded before you will load the data stored in the localstorage or in the database.
If you're using ui.router, then you should take a look at ui.router extras, specifically the sticky states module. This allows you to cache the state 'tree' (including rendered views) so they don't have to be compiled or re-rendered on state changes.
http://christopherthielen.github.io/ui-router-extras/
Here's a demo:
http://christopherthielen.github.io/ui-router-extras/example/sticky/#/
Assuming a JavaScript-based single-page application is returned by the server on the initial request. Besides some initialization code, which is common for every application, just the portion of the application needed to show the requested page (e.g. index page) is returned by the server on the initial request (then cached and rendered).
As the user clicks through the application, other portions of the application should be asynchronously loaded ('fetched', 'requested' or however you wanna call it) from the server. By "portions" a mean javascript code, images, css, etc. required to render the page. Let's focus on the javascript code part in this discussion.
It's important to notice that the javascript code to be returned to the browser is not contained in separate (static) files (which would be easy then and might be the case in the future due to e.g. performance reasons), but rather in one file, so it's not a 1:1 assiociation (request : file).
E.g. we could have a single app defined like this:
var LayoutPresenter = App.Presenter.extend('LayoutPresenter', {
__view: '<div>{{link "Author" "/author"}} - {{link "Book" "/book"}}</div>'
});
var AuthorPresenter = App.Presenter.extend('AuthorPresenter', {
__view: '<div><h1>{{name}}</h1></div>',
__parent: LayoutPresenter,
__context: { name: "Steve" }
});
var BookPresenter = App.Presenter.extend('BookPresenter', {
__view: '<div><h1>{{title}}</h1></div>',
__parent: LayoutPresenter,
__context: { title: "Advanced JavaScript" }
});
App.Presenter is part of the library I am writing and is available in the browser (or on any other client).
So assuming the user is browsing to the Book page which hasn't be loaded before (neither initially nor cached in the browser), the BookPresenter code, which is a function, should be returned by the server (assuming the LayoutPresenter code is already available in the browser and App.Presenter is available anyway because it's part of the library). I am running node.js on the server side.
How would you recommend to address this problem?
There is the eval function, so one could send javascript as a string and bring it back to live using eval(), but such an approach seems to be bad practice.
Never use eval - it's evil. The better option would be use jQuery ajax and set the dataType as script. This will evaluate your js, and also provide you with a call back once the script is loaded.
Refer to Ajax dataTypes and jQuery getScript shorthand. This is of course assuming that you can separate your code into logical modules
You might also consider it worth your time to check this question (How can I share code between Node.js and the browser?)
dNode is an option that is described in the question above and it looks quite exciting in terms of possibilities. You could create a list of function required for the Book page, then call them right off the server itself. That would eliminate the need to maintain separate js modules for each section of your page. Kudos to #Caolan for suggesting it.
As interesting as it is, take care to properly scope your functions; you don't want random users playing around on your server.
I'm trying to load and parse json data from an external source into a table via Knockout JS. So far, everything has been successful through the following code:
// Snippet
var self = this;
self.notices = ko.observableArray([]);
self.currentTab = ko.observable(5);
ko.computed(function() {
$.getJSON('http://json.source.here.com/tab/'+ko.toJS(self.currentTab), function(threads) {
if (threads !== null) {
self.notices(threads);
} else {
self.notices([]);
}
});
}, self.notices);
When a user clicks on a certain tab it would load the json data (forum threads) based on the selected tab value (self.currentTab) onto the table in the form of rows (self.notices).
Everything works as expected however, I noticed while browsing around other pages that do not have the above bindings, the json is still being loaded ($.getJSON is fired). I'm concerned that this may have some detrimental effects on the performance of my website as it is loading the json source even though it is not needed.
EDIT: I figured this out through Google Chrome's developer console.
I currently have my view model in a JavaScript file that is being used by every other pages as well. It consists of bindings for all the pages.
My question is, how can I load the json data on a specific page or only when the bindings are present - lazy loading? Preferably, I would like to keep all the bindings in a single JavaScript file, I do not want to separate them out and load them on a per page basis.
Here is an article that I wrote on a simliar topic a little while back: http://www.knockmeout.net/2011/06/lazy-loading-observable-in-knockoutjs.html
In your case, I think that you really want to add some guards around the $.getJSON call to ensure that it is only making AJAX requests when you are in the appropriate state (on the appropriate tab).
Along with that, the blog post describes using the deferEvaluation flag on a computed observable to ensure that the logic does not run until someone binds against the computed observable (in your case, you have an anonymous computed observable, but you could add it to your view model as a property and bind against it in your view. Without this flag, the evaluation code will run when you create the computed observable, which is not desirable in your case.
I consistently come across this code smell where I am duplicating markup, and I'm not really sure how to fix it. Here's a typical use case scenario:
Let's say we'd like to post comments to some kind of article. Underneath the article, we see a bunch of comments. These are added with the original page request and are generated by the templating engine (Freemarker in my case, but it can be PHP or whatever).
Now, whenever a user adds a comment, we want to create a new li element and inject it in the current page's list of comments. Let's say this li contains a bunch of stuff like:
The user's avatar
Their name
A link to click to their profile or send them a private message
The text they wrote
The date they wrote the comment
Some "edit" and "delete" links/buttons if the currently logged in user has permission to do these actions.
Now, all of these things were already written in our template that originally generated the page... so now we have to duplicate it inside of Javascript!
Sure, we can use another templating language - like Jquery's Template plugin - to ease the pain generating and appending this new li block... but we still end up with duplicate html markup that is slightly different because we can't use macros or other conveniences provided to us by the templating language.
So how do we refactor out the duplication? Is it even possible, or do we just put up with it? What are the best practices being used to solve this problem?
This is a common problem and becomes more obvious as the UI complexity increases, and changes have to be done on both the server and client templates. This problem is fixable by using a the same template markup on both the client and server sides. The template processors must be written in both JavaScript and the server side language.
Two other solutions that are cleaner than the above approach, but both have their own problems:
Do everything client side
Do everything server side
If all markup generation is done on the client side, then the server acts more or less like a web service which only sends back data in whatever formats suits the application. JSON, and XML are really popular formats for most web services nowadays. The client always generates the necessary HTML and JS. If going with this approach, the boundary between the client and server must be well defined. Since the client has limited knowledge of what happens on the server, this means that proper error codes must be defined. State management will become harder since most/all server interaction will be happening asynchronously. An example of adding a comment with this approach may look like:
$('#add-comment').click(function() {
var comment = $('#comment-box').text();
$.ajax('http://example.com/add', {
success: function() {
addCommentRow(comment);
},
...
});
});
function addCommentRow(comment) {
var user = currentUser().name;
var html = "<li><b>{user}</b> says {comment}</li>";
html = html.replace("{user}", user).replace("{comment}", comment);
var item = $('<li>').html(html);
$('#comments').append(item);
}
The other approach is to do everything server side. Whenever a change happens, shoot a request to the server, and ask it for the updated view. With a fast backend, response times under a second, and proper indicators of network activity, the application should seem very responsive despite everything happening on the server. The above example would be simplified to:
$('#add-comment').click(function() {
$.ajax('http://example.com/add', {
success: function(response) {
$('#comments').html(response);
},
...
});
});
Although this seems a lot more cleaner on the client side than the previous approach, we have just moved the markup generation up to the server. However, if the application is not very AJAXy like Google Maps, then this approach may be easier to work with. Again, it's a matter of how complicated the application is, and perhaps maintaining state client side is a necessity for you, in which case you may want to go with the previous approach.