There is basic persistence of Javascript vars/etc. You call a function/method, and the next time you call that same function/method, it is holding the data from the last time.
You can delete the vars when you are done with them, but that removes the advantage of using the code again for that instance.
So what is the proper way to write code which can be reused, on different elements, inside the same page.
Therefore, I need the ability to write code so that I can point it at several different elements, and then interact with that code segregated for each element.
So in PHP (as an example) I would do:
$element1 = new MyClass();
$element2 = new MyClass();
$element3 = new MyClass();
in that case it's the same code running in three segregated scopes. How can I do this properly with JS. Even using jQuery's extend() gives me problems.
Thanks.
Use the var keyword when defining local variables (otherwise they'll default to globals).
function foo() {
var i;
// code code code code
}
To create an instance in JavaScript you need to write a constructor function, and call that using new. For instance:
function MyClass( somevalue ) {
this.somevalue = somevalue;
this.somefunction = function() {
alert(somevalue);
}
}
var instance1 = new MyClass(1);
var instance2 = new MyClass(2);
var instance3 = new MyClass(3);
You can namespace your JavaScript to make it a lot like what you're after. See below for an example. It does sound like your problem is related to using global variables where you want to use local variables though - i.e. you declare var myvariable; outside of your function, but only want to use it and forget it within your function. In that case, declare the variable inside your function to make it local.
var MyNameSpace = function() {
return {
sayhello : function() {
alert("hello");
},
saygoodbye : function() {
alert("see ya");
}
};
}();
It sounds like what you're looking for is the ability to have instances of a class and have private data that's associated with each instance.
You can do this using the following technique:
function Foo()
{
// Member variable only visible inside Foo()
var myPrivateVar;
// Function only visible inside Foo()
var myPrivateFunction = function()
{
alert("I'm private!");
}
// Member variable visible to all
this.myPublicVar = "Hi, I'm public!";
// Function visible to all
this.myPublicFunction = function()
{
myPrivateVar = "I can set this here!";
}
}
You can create and use one of these using the following syntax:
var myFoo = new Foo();
myFoo.myPublicVar = "I can set this!";
myFoo.myPublicFunction();
Related
how to define function name (in PHP) using variable, like this?
$a='myFuncion';
function $a() {.......}
or like that?
The only way I know to give a fixed name to a function is to use eval, which I would not suggest.
More likely, what you want is to stuff a function IN a variable, and then just call that.
Try this:
$a = function() {
echo 'This is called an anonymous function.';
}
$a();
EDIT:
If you want to be accessible from other files, then use GLOBAL variable:
$GLOBALS['variable_name'] = 'my_func_123';
${$GLOBALS['variable_name']} = function() {
echo 'This is called an anonymous function.';
};
// Executing my_func_123()
${$GLOBALS['variable_name']}();
See also: http://php.net/manual/en/functions.anonymous.php
I'm trying to solve a problem in ajax which is coming out from the moment that my client asked me to not use any framework for web applications.
I have always used CodeIgniter and I never had any problem with ajax requests, especially when I had to call a method simply perform this call:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
//http://localhost/App_Name/application/controllers/user.php/ajax_check_login <-postUrl content
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// do stuff...
});
How you can see from the code above what I want to do is call a method within the controller user.php whose name is ajax_check_login.
What I have done so far to achieve the desired result is to make this code:
$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
$user = new User();
$user->$func();
}
if you want to see the complete structure of a class click here.
The problem is that this code should be placed inside each controller,
and you have to set all the methods offered, sometimes the function available reaching fifty, leads to discard this solution...
What I want to know is: how can I make a wrapper, a class that allows me to invoke a method of the controller from url and execute it?
Before all this work was done by CodeIgniter. So now I have to write my own class that allows me to access the controls easily and recall methods in different classes.
All classes that have to respond to ajax request reside in application/controllers / ... folder. In the controllers folder I have 20 controllers.
You can add ajax.php:
<?php
preg_match_all('/([^\/.]*)\.php\/([^\/]*)$/', $_SERVER['REQUEST_URI'], $matches);
$class = $matches[1][0];
$func = $matches[2][0];
$allowed_classes = array('user','account','foo');
if (isset($class) && isset($func) && in_array($class, $allowed_classes)) {
require_once "application/controllers/" . $class. ".php";
// here you could do some security checks about the requested function
// if not, then all the public functions will be possible to call
// for example if you don't want to allow any function to be called
// you can add a static function to each class:
// static function getAllowedFunctions() {return array('func1','func2');}
// and use it the same way you had checked it in the question
$obj = new $class();
$obj->$func();
// or if need to pass $_POST:
// call_user_func(array($obj, $func, $_POST));
}
and in javascript post to:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/ajax.php/user.php/ajax_check_login';
If you have apache, then you might be able to do it even without adding ajax.php by adding this to .htaccess in the controller directory:
RewriteEngine On
RewriteBase /baseUrl.../application/controllers/
RewriteRule ^([^\.]*\.php)/[^/]*$ ajax.php?file=$1&func=$2
Of course you need your real baseUrl there. And change the 1st 3 lines in the php to:
$class = $_GET['class'];
$func = $_GET['func'];
So I basically want to do this:
$this->container['Menu_builder'] = $this->container->factory(function ($c) {
return new Menu_builder($parameter_1, $parameter_2);
});
Where $parameter_1 and $parameter_2 are passed in from the call, like this:
$menu_builder = $this->container['Menu_builder']('account', 'reset_password');
I know the above syntax is incorrect, but I want to pass these strings into the call to $this->container->factory.
Is this possible?
For example, if I wanted to instantiate the Menu_builder from various controller functions with different parameters for each controller function.
FWIW, you can also include an anonymous function within your container.
$this->container['Menu_builder'] = function() {
// do stuff here
return function($parameter_1, $parameter_2) {
return new Menu_builder($parameter_1, $parameter_2);
};
};
Use this way:
$localfunc = $this->container['Menu_builder'];
$result = $localfunc($parameter_1, $parameter_2);
Notice that in this case I'm not using a factory. That's because you can execute the anonymous function with different values each time.
You just can use use() to pass your variables to the anonymous functions, e.g.
//your parameters needs to be defined here:
$parameter_1 = "XY";
$parameter_2 = 42;
$this->container['Menu_builder'] = $this->container->factory(function ($c)use($parameter_1, $parameter_2) {
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See here
return new Menu_builder($parameter_1, $parameter_2);
});
When I try to pass the url value to the controller action, action is not getting the required value.
I'm sending the value like this:
function value(url,id)
{
alert(url);
document.getElementById('rating').innerHTML=id;
var params = 'artist='+id;
alert(params);
// var newurl='http://localhost/songs_full/public/eslresult/ratesong/userid/1/id/27';
var myAjax = new Ajax.Request(newurl,{method: 'post',parameters:params,onComplete: loadResponse});
//var myAjax = new Ajax.Request(url,{method:'POST',parameters:params,onComplete: load});
//alert(myAjax);
}
function load(http)
{
alert('success');
}
and in the controller I have:
public function ratesongAction()
{
$user=$_POST['rating'];
echo $user;
$post= $this->getRequest()->getPost();
//echo $post;
$ratesongid= $this->_getParam('id');
}
But still not getting the result.
I am using zend framework.
Need alot more information here... How are you calling these functions? Are the values being passed at any stage in the chain? You mention "action", what are you actually referring to?
Further on that - if you mean that the values are not being handled within the PHP section, are you using the correctly named parameters? I see your Javascript code mentioned one parameter called "artist", but the PHP code mentions "rating" alone.
I'm using Actionscript 2.0 in combination with PHP, now I can make a call to my PHP file and receive data but apparently I have to use that data immediately, I cannot use it to fill my class variables.
This is what I want :
class user {
var lastname:String;
function user(in_ID:Number){
var ontvang:LoadVars = new LoadVars();
var zend:LoadVars = new LoadVars();
zend.ID = in_ID;
zend.sendAndLoad("http://localhost/Services/getUser.php", ontvang, "POST");
ontvang.onLoad = function(success:Boolean) {
if (success) {
lastname = ontvang.lastname;
} else {
lastname = 'error';
}
};
}
}
I've found out that this is a big issue in AS2, I found this post to work around it if you're loading XML data but I can't seem to get it to work with LoadVars :
http://www.actionscript.org/forums/showthread.php3?t=144046
Any help would be appreciated ..
When your onLoad handler is called, it is being called as if it were a member function of the LoadVars instance, and not your user instance.
There are several ways around this, one is to use Delegate.create() to create a function which will work as intended, for example:
import mx.utils.Delegate;
class user {
var lastname:String;
var ontvang:LoadVars;
function user(in_ID:Number){
ontvang = new LoadVars();
var zend:LoadVars = new LoadVars();
zend.ID = in_ID;
ontvang.onLoad = Delegate.create(this, onLoad);
zend.sendAndLoad("http://localhost/Services/getUser.php", ontvang, "POST");
};
}
function onLoad(success:Boolean) : Void
{
if (success) {
lastname = ontvang.lastname;
} else {
lastname = 'error';
}
}
}
Don't forget that the load is asynchronous - when you create one of your user objects, the member variables won't be immediately available. What you may need to do is let your user object be capable of signaling its readiness much like LoadVars does, (e.g. with a callback function provided by the caller) so that your app is driven by by these asynchronous events.