I'm trying to use a javascript var in the bean variable. This variable is the index that I need to get all values from my object. But it doesn't recognize, how can I do this? Or can you help me with an alternative solution. Thanks.
function cargarCategorias() {
while ( indice <= 5){
var valor = "#{ctrDashboard.objReporte1.get(indice)[0]}";
categorias.push(valor);
}
}
You seem to misunderstand that Java code (ctrDashboard.getObjReporte1.get(indice)[0]) operates on the server machine and JavaScript code (function cargarCategorias() { ... }) operates on the client machine within the context of webbrowser. Thus, you can't directly use these two languages interchangingly. But still, understanding lifecycle of JSF framework will help you achieve your goal.
So, your problem can be solved by using different tools. For example, if you want to preload a set of data to a JS context upon initial GET request on the page, you need to have an array of elements in JS while the page is being rendered:
<script type="text/javascript">
var valors = #{bean.valorsJson};
</script>
with bean method as:
public String getValorsJson() {
return new Gson.toJson(valorList);
}
I proposed to use Gson library for the purpose, but you're free to choose a way of creating JSON object yourself.
With this approach you will use a JavaScript variable valors for traversal in your JS function.
The similar approach can be taken if you want to update your array via AJAX.
The last thing worth noting is that this is merely a trick that is usually used to overcome a drawback in your design of JSF application. It could indicate both that you're using a wrong framework for the job mentioned and that you failed to find a proper instrument within JSF, but that's impossible to know given the information disclosed so far.
Related
Edit: apparently it's not clear, guess I'll make it more concise.
Node application is built, uses a native addon. I need to pass in a Javascript function from this project through node-addon-api into my C++ addon. Then, I need to be able to call that function from C++ multiple times. The issue arose when I found out I am unable to save the reference to the Javascript function due to the napi_env (required for calling the function) being protected from caching.
Could not find any clear answers or examples on the internet regarding how to do this, looking for tips.
Original:
as the title describes, I need to figure out a way to call a JS function multiple times in my addon. Generic use case is that my addon does some long running commands and needs to periodically push a status update back to the javascript.
I thought the best approach would be to have the user pass in a function (which just appends to a text block) for my addon to call (so it can write the updates), this way the javascript side can decide where it gets displayed.
I have experimented to get this working. Found out that my original way of saving the function in a persistent napi_value doesn't work since you cannot save napi_env as well.
I found this thread, which I think is the closest to what I need, but I can't manage to translate the Nan to napi_ so it would work with what I'm using. Callback NodeJS Javascript function from multithreaded C++ addon
Also attempted passing in an EventEmitter, but similar problem as above.
Can anyone give some pointers on if I am heading in the right direction? Perhaps help me dig up a few examples on how to accomplish this?
Your question is not clear. Assuming you are using Javascript in Node, have a look at FFI which allows one to loading and calling dynamic libraries using Javascript.
Alternatively one can just execute a function as follows from the command line:
/usr/bin/node yourjsfunctionfilehere.js
You can also pass command line parameters to the called JS function.
I'm wondering which of the following would be the best way to pass server data and use it in a function, especially if the function is to be used by a component
Method 1
function doSomething(elm, serverTime) {
// Do something
}
<script>
doSomething('foo', '<% php server time %>');
</script>
vs
Method 2
<div id="foo" data-server-time="<% php server time %>"></div>
function doSomething(foo) {
var serverTime = getElementById("server-time").dataset.servertime;
// Do something
}
<script>
doSomething('foo');
</script>
Method 3
Other suggestions?
Would like to do something like the following but not sure how?
document.getElementById("foo").doSomething() ?
For me, case 1 would be better.
code would have less coupling
code would not use global vars (document.getElementById)
you could reuse your function in other places that do not have DOM, like in the server.
I would argue in this case the 1st is better in this simple example because sever time isn't really attached to any specific div element.
Just make sure no matter what you do that there are no XSS security holes.
You are at a crossroads looking for common practice, to which one isn't more prevalent over another. Any great sage may tell you, which you choose isn't as important as making the same choice again; that is, be consistent.
Depending on the type of information, I would either pass it in the:
HTTP header (e.g., via HTTP Cookie)
Querystring (if redirection is used)
External JSON file (e.g., server.json), loaded via JS
Embedded JSON object (e.g., window.SERVER = {'server_time': <%php ...%>};)
In your case, keeping it closer to the JavaScript makes more sense and is easier to maintain, if the JS is the main place you're working. Therefore, Method 1 is both cleaner and easier to make changes in the future. Method 2, would require sifting through the HTML and making sure you are modifying the correct line.
Though, I'm somewhat partial to keeping server data as an external JSON, or embedded JSON object. So if you needed to track other server data/metadata, it's easy to add to it.
I would argue that all of them are the same and depending on your coding manner, they woulh have the same performance performand.
Let's not forget that nowadays, the most common way is to attach event listeners to elements (jQuery, Angular and .., use heavily event listeners).
I am writing a piece of javascript (ecmascript) within a 3rd-party application which uses embedded Rhino. The application may start multiple Java threads to handle data concurrently. It seems that every Java thread starts its own embedded Rhino context which in turn runs my script.
The purpose of my script is, to receive data from the application and use it to maintain the contents of a particular file. I need a fail-safe solution to handle the concurrency from my script.
So far, what I have come up with is to call out to java and use java.nio.channels.FileLock. However, the documentation here states:
File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
Sure enough, the blocking call FileChannel.lock() does not block but throws an exception, leading to the following ugly code:
var count = 0;
while ( count < 100 )
{
try
{
var rFile = new java.io.RandomAccessFile(this.mapFile, "rw");
var lock = rFile.getChannel().lock();
try
{
// Here I do whatever the script needs to do with the file
}
finally
{
lock.release();
}
rFile.close();
break;
} catch (ex) {
// This is reached whenever another instance has a lock
count++;
java.lang.Thread.sleep( 10 );
}
}
Q: How can I solve this in a safe and reliable manner?
I have seen posts regarding Rhino sync() being similar to Java synchronized but that does not seem to work between multiple instances of Rhino.
UPDATE
I have tried the suggestion of using Synchronizer with org.mozilla.javascript.tools.shell.Global as a template:
function synchronize( fn, obj )
{
return new Packages.org.mozilla.javascript.Synchronizer(fn).call(obj);
}
Next, I use this function as follows:
var mapFile = new java.io.File(mapFilePath);
// MapWriter is a js object
var writer = new MapWriter( mapFile, tempMap );
var on = Packages.java.lang.Class.forName("java.lang.Object");
// Call the writer's update function synchronized
synchronize( function() { writer.update() } , on );
However I see that two threads enter the update() function simultaneously. What is wrong with my code?
Depending how Rhino is embedded, there are two possibilities:
If the code is executed in the Rhino shell, use the sync(f,lock) function to turn a function into a function that synchronizes on the second argument, or on the this object of its invocation if the second argument is absent. (Earlier versions only had the one-argument method, so unless your third-party application uses a recent version, you may need to use that or roll your own; see below.)
If the application is not using the Rhino shell, but using a custom embedding that does not include concurrency tools, you'll need to roll your own version. The source code for sync is a good starting point (see the source code for Global and Synchronizer; you should be able to use Synchronizer pretty much out-of-the-box the same way Global uses it).
It is possible that the problem is that the object on which you are trying to synchronize is not shared across contexts, but is created multiple times by the embedding or something. If so, you may need to use some sort of hack, especially if you have no control over the embedding. If you have no control over the embedding, you could use some kind of VM-global object on which to synchronize, like Runtime.getRuntime() or something (I can't think of any that I immediately know are single objects, but I suspect several of those with singleton APIs like Runtime are.)
Another candidate for something on which to synchronize would be something like Packages.java.lang.Class.forName("java.lang.Object"), which should refer to the same object (the Object class) in all contexts unless the embedding's class loader setup is extremely unusual.
I am trying to find the best methodology and have the cleanest code as possible on a project that I am working on.
I am using php and jQuery and displaying information on the page via ajax. When something changes on the page, some of the variables that are passed back into the page change. I need to store these values for other scripts on the page to use. What is the best approach for this.
Currently I am just storing these variables in hidden input fields with id's and then using jQuery to access them when needed. Is this a good approach or is there a better methodology? I don't want to have junky code that other developers look at and use and their punch line to their jokes.
Thanks!
I find storing the variables inside your script is faster, especially since you're using them with existing JS. I would go further than some of the comments, however. If you're working with a series of fields and methods, it's best to build a JS object and keep everything together. This has the added benefit of being viewable inside your DOM inspector (Firebug, etc).
function MyClass(obj) {
this.myvar = obj.val
}
MyClass.prototype.myFunc() {
console.log(this.myvar);
}
newobj = new MyClass({"val":1});
newobj.myFunc();
You can make use of HTML5 sessionStorage object
an example of how you set it
sessionStorage.setItem("myKey", "myValue");
please check documentation below
Here
I have an update query to which I am passing a JavaScript array called "newdata", obviously, that didn't work so I don't know how to pass my JavaScript variables to ColdFusion in order to run an update query. How I can see surfing some webs? ColdFusion doesn't have access to Javascript variables. Here's my code, regards!
<cfquery name="updatereserva" datasource="Prueba">
UPDATE reserva_habitac
SET FechaENTRADA = newdata["#firstdate#"]
WHERE idRESERVA = newdata["idreserva"]
</cfquery>
Is there another way to do this?
There are several ways.
You could put the JavaScript variables into a form, and submit that to a specific page in your app.
You could execute an AJAX request that posts your JavaScript array as JSON to the desired page in your application
Etc.
ColdFusion has some built in support for AJAX, but there are also a ton of JS libraries and frameworks that could do just as good (if not way better) of a job. There is, after all, nothing ColdFusion-specific about an AJAX request; CF just ships with some functionality to help, if you want to use that.
The important thing is that in designing your app, you need to remember that JavaScript and ColdFusion operate in different contexts--the former on the client (browser), the latter on the server. While this is certainly not an impediment to making a very robust JavaScript-fronted app (or even an app that just used JavaScript here and there to talk to ColdFusion), you do have to design a bit differently than you would with a non-JS app, so it's important to get the difference clear and go from there.