How to pass function to client from Node.js server - javascript

All:
What I want to do is like:
On Node server side:
var fn = function(){
alert("hello");
}
I want to send this function to client side(currently using AngularJS, but it does not matter as long as this problem can be solved), and bind it to a button click event. So I can get pop-out alert window when click that button.
Thanks

So, something like this:
// Predefined functions
var allowedFunctions = {
'f1': function () {alert('Called f1');},
'f2': function () {alert('Called f2');},
'f3': function () {alert('Called f3');},
};
// This comes from the server
var callThisOne = 'f2';
// Here's how you call it now
allowedFunctions[callThisOne]();

Here's a plunk.
// Get this from the server
var textReceived = 'var fn = function(){ alert("hello"); };';
function getFunction(textReceived) {
eval(textReceived);
return fn;
}
var f = getFunction(textReceived);
f();

Related

JavaScript Scope of Vaadin's "AbstractJavaScriptComponent"

I have integrated some HTML/JS Code into my Vaadin WebApplication by creating an AbstractJavaScriptComponent. The Component almost works as intended.
How do I call the passInfo() method defined in the "connector.js" without having to manually click the Button defined in the innerHTML of the "chessControll.JsLabel" Component in "chessControll.js". My Goal is to pass Information, when the onChange Event of the init() function is called, which is located in the same file "chessControll.js", but not part of the Component.
I have already tried to create a Custom Event and then dispatch it whenever onChange() in the init() function is called, it worked as long as I didn't listen for the Event inside of my Component (chessControll.js, chessControll.JsLabel). It seems it can only be accessed in a static way.
How can I access the chessControll.JsLabel in "chessControll.js" from the init() function and then dispatch the button click or listen for events inside the component to achieve the same?
connector.js:
com_*myname*_*applicationName*_JsLabel = function() {
var mycomponent = new chessControll.JsLabel(this.getElement());
connector = this;
this.onStateChange = function() {
mycomponent = this.getState().boolState;
};
mycomponent.click = function() {
connector.passInfo(true);
};
};
chessControll.js:
var chessControll = chessControll || {};
chessControll.JsLabel = function (element) {
element.innerHTML =
"<input type='button' value='Click'/>";
// Getter and setter for the value property
this.getValue = function () {
return element.
getElementsByTagName("input")[0].value;
};
var button = element.getElementsByTagName("input")[0];
var self = this;
button.onclick = function () {
self.click();
};
};
var init = function() {
var onChange = function() {
/*Click Button defined in JsLabel Component */
};
};$(document).ready(init);
I figured out what the problem was.
The architecture of Java Web Applications doesn't allow a simple communication like i did in my example. The JavaScript made a call from the Client Side to the Server Side Vaadin Component.
I integrated the whole JavaScript, including the init function, as a Component. This way i can call the method from the init function because everything is known on the Server Side.
edited chessControll.js :
var chessControll = chessControll || {};
chessControll.JsLabel = function (element) {
element.innerHTML =
"<input type='button' value='Click'/>";
// Getter and setter for the value property
this.getValue = function () {
return element.
getElementsByTagName("input")[0].value;
};
var button = element.getElementsByTagName("input")[0];
var self = this;
//deleted bracket here
var init = function() {
var onChange = function() {
self.click();
};
};$(document).ready(init);
} //<-- that Simple

Avoid Jquery self calling function

I got below a Jquery function to switch between two buttons simultaneously but it's a "dirty" way of writing the code my boss will say. I don't wanna call the functions or no passing in Jquery parameter, is the there a simple or better way to write this function since i'm totally new to programming?
Below the Jquery
var startStopBtn = function () {
var startBtn = $('#timerStart');
var stopBtn = $('#timerStop').hide();
var Start = function () {
startBtn.hide();
stopBtn.show();
};
var Stop = function () {
var remarks2 = $(".textArea-one").val();
if (remarks2 !== "") {
startBtn.show();
stopBtn.hide();
}
};
return {
Start: Start,
Stop: Stop
};
}(jQuery);
jQuery('#timerStart').on('click', startStopBtn.Start);
jQuery('#timerStop').on('click', startStopBtn.Stop);
I think code could be done in many ways, this is just one of them.
Looks like first you want to hide the stopBtn so create a function to do this. Call that function on page load or create a funtion and call it when the page loads. Here I create a function that you should call whenever you want. If you don't want to do that, just delete that function.
Then make two diferent functions that are done when you "click" #timerStart or #timerStop.
This is my version but i'm sure it can be improved:
function startStopBtn(){
$('#timerStop').hide();
};
$('#timerStart').on('click', function(){
$('#timerStart').hide();
$('#timerStop').show();
});
$('#timerStop').on('click', function(){
var remarks2 = $(".textArea-one").val();
if (remarks2 !== "") {
$('#timerStart').show();
$('#timerStop').hide();
}
});

Referencing another function in array of functions

I'm using require.js and have a library of functions I use in multiple places. I define the functions thusly:
define(function (require) {
"use strict";
var $ = require('jquery');
var UsefulFuncs = {};
UsefulFuncs.hideAlert = function() {
$('.alert').hide();
};
UsefulFuncs.loadURL = function (url){
navigator.app.loadUrl(url, { openExternal:true });
return false;
};
UsefulFuncs.linkClicked = function (e) {
e.preventDefault();
var url = $(e.currentTarget).attr("rel");
this.loadURL(url);
};
return UsefulFuncs;
});
Then, in my backbone view, I call a function from the library with:
UsefulFuncs = require('app/utils/useful_func'),
....
UsefulFuncs.linkClicked
This works fine for any standalone function in the library e.g. hideAlert(). However when one function in the library refers to another, such as linkClicked() calling loadURL(), I get an error:
Uncaught TypeError: Object [object Object] has no method 'loadURL'.
Any ideas how I can reference loadUrl()?
I would assume you set UsefulFuncs.linkClicked as a handler for an event.
If you were to use it like this:
UsefulFuncs.linkClicked()
, this inside the function would refer to UsefulFuncs, so this.loadURL() would be valid.
However, since you set it as a handler for an event, it can be called in other ways, and this is set to some other object (probably the element which triggered the event). To avoid the event handling mechanism changing your this, you can bind the function when you assign it:
element.onclick = UsefulFuncs.linkClicked.bind(UsefulFuncs);
Another way to go around it is to avoid using this in the handler, like so:
UsefulFuncs.linkClicked = function (e) {
e.preventDefault();
var url = $(e.currentTarget).attr("rel");
UsefulFuncs.loadURL(url);
};
This creates a closure over UsefulFuncs (the first method does as well, but it's more standardized).
Try something like this:
define(function (require) {
"use strict";
var $ = require('jquery');
var hideAlert = function() {
$('.alert').hide();
};
var loadURL = function (url){
navigator.app.loadUrl(url, { openExternal:true });
return false;
};
var linkClicked = function (e) {
e.preventDefault();
var url = $(e.currentTarget).attr("rel");
loadURL(url);
};
return {
hideAlert : hideAlert,
loadURL : loadURL,
linkClicked : linkClicked
};
});

Titanium mvc - call function and wait for result

I am currently in the process of making my first Titanium iPhone app.
In a model I got:
(function() {
main.model = {};
main.model.getAlbums = function(_args) {
var loader = Titanium.Network.createHTTPClient();
loader.open("GET", "http://someurl.json");
// Runs the function when the data is ready for us to process
loader.onload = function() {
// Evaluate the JSON
var albums = eval('('+this.responseText+')');
//alert(albums.length);
return albums;
};
// Send the HTTP request
loader.send();
};
})();
and I call this function in a view like:
(function() {
main.ui.createAlbumsWindow = function(_args) {
var albumsWindow = Titanium.UI.createWindow({
title:'Albums',
backgroundColor:'#000'
});
var albums = main.model.getAlbums();
alert(albums);
return albumsWindow;
};
})();
however it seems like the call to the model (which fetches some data using HTTP) doesn't wait for a response. In the view when I do the alert it haven't received the data from the model yet. How do I do this in a best-practice way?
Thanks in advance
OK,
Something like this,
function foo(arg1, callback){
arg1 += 10;
....
... Your web service code
....
callback(arg1); // you can have your response instead of arg1
}
you will call this function like this,
foo (arg1, function(returnedParameter){
alert(returnedParameter); // here you will get your response which was returned in above function using this line .... callback(arg1);
});
so here arg1 is parameter (simple parameter like integer, string etc ... ) and second argument is your call back function.
Cheers.
What you need is Synchronous call to web service, so that it will wait till you get the response from the service.
To achieve this in java script you have to pass callback function as parameter and get the return value in callback function instead of returning value by return statement.
Actually coding style you are using is new for me because i am using different coding style.
But the main thing is you have to use call back function to retrieve value instead of return statement. Try this and if you still face the problem than tell me i will try to give an example.
the callback way like zero explained is nicely explained, but you could also try to get it handled with events.
(function() {
main.ui.createAlbumsWindow = function(_args) {
var albumsWindow = Titanium.UI.createWindow({
title:'Albums',
backgroundColor:'#000'
});
var status = new object(), // eventlistener
got_a_valid_result = false;
// catch result
status.addEventListener('gotResult',function(e){
alert(e.result);
got_a_valid_result = true;
});
// catch error
status.addEventListener('error',function(e){
alert("error occured: "+e.errorcode);
git_a_valid_result = true;
});
var albums = main.model.getAlbums(status);
// wait for result
while (!got_a_valid_result){};
return albumsWindow;
};
})();
and your model may something like
main.model.getAlbums = function(status) {
var loader = Titanium.Network.createHTTPClient();
loader.open("GET", "http://someurl.json");
loader.onload = function() {
var albums = eval('('+this.responseText+')');
status.fireEvent('gotResult',{result:albums});
return albums;
};
loader.onerror = function(e){
status.fireEvent('error',{errorcode:"an error occured"});
};
// Send the HTTP request
loader.send();
};
Just as a suggestion, try to use JSON.parse instead of eval as there are risks involved with using eval since it runs all javascript code.
I think that the solution The Zero posted is likely better for memory management, but I'm not totally sure. If you do and eventListener, be aware of the following
(see https://wiki.appcelerator.org/display/guides/Managing+Memory+and+Finding+Leaks)
function doSomething(_event) {
var foo = bar;
}
// adding this event listener causes a memory leak
// as references remain valid as long as the app is running
Ti.App.addEventListener('bad:idea', doSomething);
// you can plug this leak by removing the event listener, for example when the window is closed
thisWindow.addEventListener('close', function() {
// to remove an event listener, you must use the exact same function signature
// as when the listener was added
Ti.App.removeEventListener('bad:idea', doSomething);
});

jQuery binding function on focus

I'm writing a little plugin for jQuery and so far I've got this:
(function($){
$.fn.extend({
someFunction: function() {
return this.each(function() {
var obj = $(this);
obj.focus(someInternalFunction(obj));
});
}
});
function someInternalFunction(obj) {
};
})(jQuery);
The problem is, when i attach someFunction to the object, the object gets focus and binding of someInternalFunction on focus event fails.
Then I tried to bind function to wrap the function call in the other function:
obj.focus(function() {
someInternalFunction($(this));
});
This code works, but it isn't pretty at all. Is it possible to bind function on focus without wrapping it in the other function?
$.fn.bindFocus() = function(){
var internalFunction = function(){
var $this = $(this),
self = this;
// try do stuff here
};
return this.each(function(){
$(this).bind('focus', internalFunction);
});
}
$('#myElement').bindFocus();
Hope it'll help ?
EDT. Sorry, first time get you wrong :)
Here:
obj.focus(someInternalFunction(obj));
^^^^^
... you're calling the function, meaning that its return value is the thing that actually ends up being passed to focus(). Instead you want to pass a function to focus(). Given the fact that you want to pass obj to someInternalFunction, you'll have to define an additional function to wrap it all:
obj.focus(function(){
someInternalFunction(obj);
});
Just to make things clear:
var x = function() { return 3; }; // Defining a function
x; // -> this is a function reference
x(); // -> this is 3

Categories

Resources