Table of Contents
Automated MVC execution
Extend your client-side module functionality with javascript application client.
Simply apply it inside frontend.js or admin.js autoloaded assets.
Example:
App.module.extend({
// extend your module "module_name"
module_name: {
controllers: {
// on Index controller
index : {
// executes in all actions
_init : function() {
App.onReady(function(){
// code here
});
},
// executes in Index action
index : function() {
App.onReady(function(){
// code here
});
}
}
}
}
});
App.reinit();
Anytime when extended controller/action is called javascript code will executed.
Use App.onReady(function() { ... }); construction inside action declarations to execute code on document ready.
Note!
Don't forget to use App.reinit() after extending your module.
Configuration
Application client has automatic configuration principle. All common config parameters has configured by Singular_Controller_Plugin_AppClient controller plugin when postDispatch process has started.
As for now application client has one config param that can be changed.
App.config.ajax.useDefaultEventHandlers
default value: true
By changing this param you can switch off/on default preloader when ajax request is occured
Note!
Don't forget to use App.reinit() when changing config params for applying their new values.
Getting/setting global params
Application client provides several methods to manipulate global parameters that was set via PHP environment or Javascript.
Setting javascript params using Singular_AppClient.
You can use following construction inside any place of code, such as action, component, model, library and so on:
$username = 'faustman';
Singular_AppClient::setParam('username', $username);
So, now you can easily access your defined param from javascript:
var username = App.getParam('username');
Also you can use default value for param name if it's not set:
var username = App.getParam('username', 'anonymous');
Managing params:
|
With Singular_AppClient |
With JS Application client |
Description |
|
setParam($name, $value) |
App.addParam(name, value) |
Sets param $name. $value can be string, integer, array or simple object like stdClass. |
|
getParam($name) |
App.getParam(name, _default) |
Returns param by key $name. |
|
hasParam($name) |
App.hasParam() |
Returns TRUE if the $name is a named value in the storage, or FALSE if $name was not found in the storage. |
|
hasParams() |
App.hasParams() |
Checks if one or more params has set and param storage is not empty. |
|
getAllParams() |
App.getAllParams() |
Returns all params as array. |
|
clearAllParams() |
— |
Clears all stored params. |
Standart getters
In some cases you may need to get current module/controller/action name and so on for advanced programming. So this standart getters may help you.
App.getModuleName()
Returns current module name.
App.getControllerName()
Returns current controller name.
App.getActionName()
Returns current action name.
App.baseUrl(path)
Returns application baseUrl.
If you need to correctly make path to url or route see example below:
var userAvatar = App.baseUrl('user/f/id7004955301.jpg');
$('#profile-block').find('img.avatar').attr('src', userAvatar);
App.getVersion()
Returns current application client version.
Utilities
There are some useful utilities as part of application client core. Our team plan to add one more in our future releases. So, lets describe available.
App.utils.xml2Json(xml)
Converts xml string into native JSON notation.
var xmlString = ''; var jsonObj = App.utils.xml2Json(xmlString); /* jsonObj now contains: { animals:{ dog:[ { name:'Rufus', breed:'labrador' }, { name:'Marty', breed:'whippet' } ], cat:{ name:'Matilda' } } } */ Rufus labrador Marty whippet
App.utils.scrollTo(element, duration)
Scrolls to specified element with given duration. Default duration value is 300ms.
$('#goto').click(function() {
App.utils.scrollTo('div.cart', 500);
});
App.utils.timer(funct, msec)
Calls a function or evaluates an expression after a specified number of milliseconds.
App.utils.camelToDash(str)
Converts a camelcase to dashes. For eg: if the string has a camelcase in it - like "viceVersa", the result expected is "vice-versa".
var str1 = "devCurry"; str1 = App.utils.camelToDash(str1); alert(str1); // result: dev-curry
App.utils.dashToCamel(str)
Converts a dashes to Camelcase. Similarly if a string has a dash in it, like "dot-net", the result expected is "dotNet".
var str2 = "dev-curry"; str2 = App.utils.dashToCamel(str2); alert(str2); // result: devCurry
str2 = App.utils.dashToCamel(str2);
Logging
Logging mechanism represents as wrapper for console.log() construction. You can use it for for debugging your variables, objects or output as simple as var_dump() or print_r() functions in PHP.
App.log(variable, [variable], [...])
You can pass as many arguments as you want and they will be joined together in a row, like App.log(2,4,6,8,"foo",bar).
var saySomethingClever = (function(){
var appleTest = /Apple/i;
var googleTest = /Google/i;
if( appleTest.test(navigator.vendor) )
return function(){ App.log("I love apples <3"); }
if( googleTest.test(navigator.vendor) )
return function(){ App.log("android is everything for me <3"); }
return function(){ App.log("i love this unpopular corporation too"); }
})();
Making Ajax requests
Ajax adds a layer to web application communication models. As previously stated, in traditional web applications communication between the browser/client and the web server occurred directly between these two components using HTTP requests. When users/clients request web pages, the server sends all the HTML and CSS code at once. If the user enters information into this page and requests more servers, the entire page must be loaded again. When using Ajax, the page is only loaded once. Any processing or modification caused by additional user input occurs in real time.
There are several ways to handle and process Ajax requests using javascript application client in couple with Singular "Autoresponder" action helper.
App.remote.load(id, url)
Simply loads response data into DOM element with specified id.
Javascript:
var url = App.baseUrl('article/id/7');
App.remote.load('article-content', url);
HTML:
Article
...
PHP:
public function arcticleAction ()
{
// Disable Layout and viewRenderer support
$this->_helper->noRender();
$id = $this->getRequest()->getParam('id');
$content = $this->articles->find($id)->current()->content;
// Disable autoresponder to preventing catching Ajax reauests
$this->autoresponder->disable();
echo $this->view->escape($content);
}
App.remote.get(url, data, callback, type)
Makes ajax request using GET method. Also you can use more convenient way: App.remote.get(params). So let's describe two use cases.
Define request URL:
var url = App.baseUrl('user/data/get');
Prepare request parameters:
var data = {
format: 'json',
id: 15,
status: $('input.f-name').val()
};
Make ajax request:
App.remote.get(url, data, function (r) {
var result = App.remote.parseResult(r);
if (result.data.isError()) {
App.notify.error(result.data.getMessage());
} else {
App.notify.success(result.data.getMessage());
}
}
If you already have noticed we are using App.remote.parseResult(r) construction. This is special application client method to parse response result data maked by "Autoresponder" controller helper that will be described below.
Ajax request passed one param "r" to callback function. This param contains response data usually in JSON format. Then we pass it to App.remote.parseResult(r) method and finally have response object which contains data manipulation methods.
Also you can build ajax request by passing object with url, callback functions and data which will be transferred by request.
Example:
var success = function(response) {
if ('auth' == response.data.getAction()) {
// you code
}
}
var complete = function(response) {
example.hideLoading();
}
var error = function(response) {
// alert error message
alert(response.data.getMessage());
}
var params = {
url: '/auth',
data: {'user_id': 5, 'format': 'json'},
success: success,
complete: complete
};
// make ajax request
App.remote.get(params);
App.remote.post(url, data, callback, type)
The same as App.remote.get() but using POST method.
Parsing Ajax response
There is one simple method to parse ajax responses that being generated with "Autoresponder".
So use App.remote.parseResult(respone) to assort response data.
Example:
Making Ajax request.
App.remote.post(
App.baseUrl('user/auth'), // URL
{username: 'davidsson', password: '12345'}, // data
function (response) { // callback function
var result = App.remote.parseResult(response);
/*
Your code...
*/
}
}
Approximately response from "Autoresponder".
{ "response" : {
"code" : 0,
"module" : "system",
"controller" : "auth",
"action" : "login",
"message" : "Login is incorrect!",
"output" : null,
"params" : { "actionName" : "login",
"defaultType" : { },
"forgotForm" : { },
"formId" : "login-form",
"url" : null
},
"response_type" : "error",
"server_time" : "Feb 13, 2012 1:47:43 PM"
} }
You can manipulate RAW result with easiest API provided by application client. Let's see on result object methods by taking "result" variable for a basis.
var result = App.remote.parseResult(response);
result.data.getServerTime()
Returns server time during request. May be used in logging system.
result.data.getType()
Returns response type that has on of two values only: "success" or "error".
Example:
Server side.
public function basicAction ()
{
/*
Your code....
*/
if (null === $found) {
$this->autoresponder->setError('There are no records');
}
}
Client side.
/*
Ajax request...
*/
var result = App.remote.parseResult(response);
switch (result.data.getType()) {
// on success
case 'success':
// Your code
break;
// on errror
case 'error':
alert(result.data.getMessage());
break;
}
/*
Your code....
*/
result.data.isError()
Returns "true" if response has error type that has been set from "Autoresponder".
result.data.isSuccess()
Returns "true" if response has success type that has been set from "Autoresponder".
result.data.getCode()
You may also specify response code for adjustment of behavior of your application. Default value is integer "0".
Example:
Server side.
public function responseAction ()
{
/*
Your code....
*/
$file = new File(APPLICATION_PATH . '/files/transport.xml');
$perm = $file->getPermission(); // 0777
$this->autoresponder->setSuccess('File has write access', $perm))
}
Client side.
/*
Ajax request...
*/
var result = App.remote.parseResult(response);
switch (result.data.getCode()) {
case '0777':
// Your code
break;
case '0755':
// Your code
break;
case '0644':
default:
// Your code
break;
}
/*
Your code....
*/
result.data.getMessage()
Returns response message that has been set from "Autoresponder".
In action on server side:
$this->autoresponder->setSuccess('Record has added');
On client side:
var message = result.data.getMessage(); alert(message); // Record has added
result.data.getOutput()
Used for getting response body text, e.g. rendered template html content.
In action on server side:
public function indexAction ()
{
$news = new News_Model_News();
$this->view->news = $news->getLast(10);
if ($this->isAjax()) {
$this->autoresponder->setOutput(
$this->fetchTemplate('last_x_news.phtml')
);
}
}
On client side:
/*
Ajax request...
*/
var result = App.remote.parseResult(response);
$('#news-widget').html(result.data.getOutput());
result.data.getModule()
Returns module name which has processed the request.
result.data.getController()
Returns controller name which has processed the request.
result.data.getAction()
Returns action name which has processed the request.
result.data.getParam(paramName)
Returns given param value from the request.
In action on server side:
$this->autoresponder->setParam('username', 'tomcat12');
$this->autoresponder->setParams(
array(
'color' => 'red',
'taste' => 'sweet',
'size' => 'big'
)
);
On client side:
/*
Ajax request...
*/
var result = App.remote.parseResult(response);
alert(result.data.getParam('username'));
var params = result.data.getParams();
/*
params contains:
{
"username" : "tomcat12",
"color" : "red"
"taste" : "sweet",
"size" : "big"
}
*/
$.each(params, function(key, value) {
alert(key + ': ' + value);
});
result.data.getParams()
Returns all response params. See result.data.getParam(paramName) for examples.