javascript code architecture question - javascript

I'm about to make a web app which will have a pretty heavy client end. I'm not sure about the way to organize my javascript code, but here is a basic idea :
// the namespace for the application
var app = {};
// ajax middle layer
app.products = {
add : function(){
// send ajax request
// if response is successful
// do some ui manipulation
app.ui.products.add( json.data );
},
remove : function(){},
...
};
app.categories = {
add : function(){},
....
};
// the ui interface which will be called based on ajax responses
app.ui = {};
app.ui.products = {
add : function( product_obj ){
$('#products').append( "<div id='"+product_obj.id+"'>"+product_obj.title+"</div>" );
}
};
app.ui.categories = {};
Anybody got similar experiences to tell me the pros and cons of this approach? What's your way of designing client side javascript code architecture? Thanks.
[update] : This web app, as you see from the above, deals with products CRUD, categories CRUD only in a ajax fashion. I'm only showing an snippet here, so you guys know what I'm trying to achieve and what my question is. Again, I'm asking for inputs for my approach to organize the code of this app.

That is similar to the way I do my JavaScript projects. Here are some tricks I have used:
Create one file for each singleton object. In your code, store ajax, middle layer and ui interface in separate files
Create a global singleton object for the 3 layers usually in the project; GUI, Backend and App
Never use pure ajax from anywhere outside the Backend object. Store the URL to the serverside page in the Backend object and create one function that uses that URL to contact the server.
Have a JSON class on the server that can report errors and exceptions to the client. In the Backend object, check if the returned JSON object contains an error, and call the serverError function in the GUI class to present the error to the user (or developer).
Here is an example of a Backend object:
var Backend = {};
Backend.url = "/ajax/myApp.php";
Backend.postJSON = function(data, callback){
var json = JSON.stringify(data);
$.ajax({
type: "POST",
url: Backend.url,
data: "json="+json,
dataType: "json",
success: function(response){
if(response){
if(response.task){
return callback(response);
}else if(response.error){
return Backend.error(response);
}
}
return Backend.error(response);
},
error: function(response){
Backend.error({error:"network error", message:response.responseText});
},
});
};
Backend.error = function(error){
if(error.message){
Client.showError(error.message, error.file, error.line, error.trace);
}
};
This can be improved by storing the ajax object somewher in the Backend object, but it's not necessary.

When you build something non trivial, encapsulation is important to make things maintainable in long run. For example, JS UI is not just simple JS methods. A UI components consists of css, template, logic, localization, assets(images, etc).
It is same for a product module, it may need its own settings, event bus, routing. It is important to do some basic architectural code in integrating your chosen set of libraries. This had been a challenge for me when I started large scale JS development. I compiled some best practices in to a reference architecture at http://boilerplatejs.org for someone to use the experience I gained.

For client-side ajax handling I have a URL object that contains all my urls and than I have an ajax object that handles the ajax. This is not a centric approach.In my case I have I have different urls handling different tasks. I also pass a callback function to be executed into the ajax object as well.
var controller_wrapper = {
controller: {
domain: "MYDOMAIN.com",
assets: "/assets",
prefix: "",
api: {
domainer: "http://domai.nr/api/json/info",
tk_check: "https://api.domainshare.tk/availability_check"
},
"perpage": "/listings/ajax",
"save_image": "/members/saveImage",
"update": "/members/update",
"check_domain": "/registrar/domaincheck",
"add_domain": "/registrar/domainadd",
"delete_listing": "/members/deactivateProfile",
"save_listing": "/members/saveProfile",
"get_images": "/images/get",
"delete_image": "/images/delete",
"load_listing": "/members/getProfile",
"load_listings": "/members/getListings",
"loggedin": "/members/loggedin",
"login": "/members/login",
"add_listing": "/members/add",
"remove": "/members/remove",
"get": "/members/get",
"add_comment": "/members/addComment",
"load_status": "/api/loadStatus"
}
}
var common = {
pager: 1,
page: 0,
data: {
saved: {},
save: function (k, v) {
this.saved[k] = v;
}
},
ajax: {
callback: '',
type: 'POST',
url: '',
dataType: '',
data: {},
add: function (k, val) {
this.data[k] = val;
},
clear: function () {
this.data = {};
},
send: function () {
var ret;
$.ajax({
type: this.type,
url: this.url,
data: this.data,
dataType: this.dataType !== '' ? this.dataType : "json",
success: function (msg) {
if (common.ajax.callback !== '') {
ret = msg;
common.ajax.callback(ret);
} else {
ret = msg;
return ret;
}
return;
},
error: function (response) {
console.log(response);
alert("Error");
}
})
}
}
var callback = function (results) {
console.log(results
}
common.ajax.callback = callback;
common.ajax.type = "jsonp";
common.ajax.type = "POST";
common.ajax.url = controller_wrapper.controller.perpage;
common.ajax.add("offset", common.page);
common.ajax.add("type", $("select[name='query[type]']").val());
common.ajax.add("max", $("select[name='query[max]']").val());
common.ajax.add("min", $("select[name='query[min]']").val());
common.ajax.add("bedrooms", $("select[name='query[bedrooms]']").val());
common.ajax.add("sort", $("select[name='query[sort]']").val());
common.ajax.send();

Related

EXTJS 4 build , singleton not called?

i am trying to make put my app in production mode , i face problem that my js code keep complain about missing javascript object and not run ,
in my app.js i have this
requires: [
"FleetM.utility.SharedData"
],
and this shared data is used in all controllers and view as singleton with name SharedData , but after build , the minified js keep say that SharedData is missing , but if i put it in console it print all values, even if i use uncompressed js the same result , here is my SharedData class
Ext.define('FleetM.utility.SharedData', {
alternateClassName: 'SharedData',
singleton: true,
'PreventALLUpdateDelete': 0,
'vehicles_creation': 0,
//..... alot of varibles here
'appSettings': 0,
'user': 0,
'i18n': 0,
success_load: false,
'comWizard': 0,
constructor: function () {
Ext.Ajax.request({
url: "USERS/GetAccessLevelData",
method: 'GET',
scope: this,
success: function (response, opts) {
var data = Ext.decode(response.responseText, true);
try {
SharedData.user = data;
SharedData.user.Connected=1;
} catch (err) {
}
try {
SharedData.PreventALLUpdateDelete = data.PreventALLUpdateDelete;
SharedData.vehicles_creation = data.vehicles_creation;
var language = SharedData.user.language;
} catch (err) {
}
switch (language) {
case '0':
language = "En";
break;
case '1':
language = "Ar";
break;
default:
language = "En";
break;
}
this.LoadI18n(language);
success_load: true;
},
failure: function (err) {
//Ext.MessageBox.alert(SharedData.i18n.Reports.ErrorMsg, SharedData.i18n.Reports.tryAgain);
}
});
},
LoadI18n: function (language) {
var me = this;
Ext.Ajax.request({
url: "data/i18n" + language + ".json",
method: 'GET',
scope: this,
success: function (response, opts) {
var data = Ext.decode(response.responseText, true);
try {
SharedData.i18n = data;
} catch (err) {
}
me.success_load = true;
},
failure: function (err) {
//Ext.MessageBox.alert(SharedData.i18n.Reports.ErrorMsg, SharedData.i18n.Reports.tryAgain);
}
});
}
});
----UPDATE----
I have done add requires for all controllers , and views , it still
complain
look at the images bellow ,
You have to add it to the requires array of each class, to have it available for all of it.
It is not enough to have it just in your app.js.
In development mode the missing class can be loaded dynamically, but in the production app.js all requires are appended in the order they need to be.
For Example: requires["C1", "FleetM.utility.SharedData", "C2"]
Would result in an app.js like
All the code with the requires for C1
All the code and requires for SharedData
All the code and requires for C2
When C1 needs SharedData for it's functionality it has to require it as well or SharedData is not available at that time for C1.
Update
You can not access the singleton FleetM.utility.SharedData during the configuration of the class, because it is not initialized during that point.
You should be able to access it in the constructor method of the store.
constructor: function() {
this.data = [
id: 0,
name: SharedData.i18n.configuration.Type_Vehicles
];
this.callParent(arguments);
}

What is the best way to add server variables (PHP) in to the Backbone.model using require.js?

I'm not sure what is the elegant way to pass server variables in to my Model.
For example, i have an id of user that has to be implemented on my Model. But seems like Backbone with require are not able to do that.
My two options are:
Get a json file with Ajax.
Add the variable on my index.php as a global.
Someone know if exists a other way. Native on the clases?
Trying to make work the example of backbonetutorials. I am not able to throw a callback when the method fetch().
$(document).ready(function() {
var Timer = Backbone.Model.extend({
urlRoot : 'timeserver/',
defaults: {
name: '',
email: ''
}
});
var timer = new Timer({id:1});
timer.fetch({
success: function(data) {
alert('success')
},
fail: function(model, response) {
alert('fail');
},
sync: function(data) {
alert('sync')
}
});
});
The ajax request it has been threw. But does not work at all. Because any alert its dispatched.
var UserModel = Backbone.Model.extend({
urlRoot: '/user',
defaults: {
name: '',
email: ''
}
});
// Here we have set the `id` of the model
var user = new Usermodel({id: 1});
// The fetch below will perform GET /user/1
// The server should return the id, name and email from the database
user.fetch({
success: function (user) {
console.log(user);
}
})
The server will reply with a json object then you can leave the rendering part for your backbone. Based on a template for the user.
You may also want to check these out: http://backbonetutorials.com/

Kendo UI treeview current datasource post

I need to create a folder structure in FTP similar to that of the tree structure on my view. I want to allow the user to edit the tree structure before creating folders.
I have a TreeView with server binding:
#model IEnumerable<TreeViewItemModel>
#(Html.Kendo().TreeView()
.Name("PipelineStructureMajor")
.BindTo(Model)
.ExpandAll(true)
.DragAndDrop(true)
)
The binding is fine. With some client-side restructuring (appending/dragging/removing some nodes), I want to post the treeview (root node with all its children recursively) to my action.
public ActionResult _CreateFtp(TreeViewItemModel root)
{
//FTPClient in action : Parsing whole tree and converting into the folder structure
return PartialView("_TreeMajor", <refreshed model>);
}
On the Client side, I tried to alert treeview data, it shows the root node text with its Items empty.
$('#createFtpConfirmed').click(function () {
//TreeView data
var treeData = $("#PipelineStructureMajor").data("kendoTreeView").dataSource.data();
alert(JSON.stringify(treeData));
$.ajax({
url:'#Url.Action("_CreateFtp", "Structure")',
data: {root: treeData},
type:"POST",
success: function (result, status, xhr) {
//Doing something useful
}
});
});
Is there a way to accomplish this?
As my question explains, I have 3 steps:
Server-bind the default tree
Edit nodes (delete, add, rename nodes)
Fetch back all treeview data (including added ones)
After going through the kendo docs and this demo, I got the point. I have to make my tree datasource observable so as to reflect the node-changes. For this I had to use kendo-web-scripts (instead of server wrappers). So I changed my step 1 to:
Remote bind the default tree (To make my dataSource observable)
I want my tree view fully loaded at once remotely and seeing this demo, I figured out that treeview only allows one level to be loaded at a time. (UserVoice already queued but Kendo team still ignoring it). So I use a hacky way:
<div id="PipelineStructureMajor"></div>
<button id="createandorinsert" class="k-button hugebtn">Send</button>
<script>
$.get("../Structure/LoadTreeData", function (data) {
var sat = new kendo.data.HierarchicalDataSource({
data: data
});
var pipelinetree = $("#PipelineStructureMajor").kendoTreeView({
dataSource: kendo.observableHierarchy(sat),
dragDrop: true,
select: onNodeSelect
}).data("kendoTreeView");
});
</script>
And I sent my data to the controller action like:
$('#createandorinsert').click(function (e) {
//TreeView's current datasource
var tree = $("#PipelineStructureMajor").data("kendoTreeView").dataSource.data();
$.ajax({
url: '../Structure/FtpCreateAndOrSync',
type: 'POST',
data: {
xmlNodes: JSON.stringify(tree)
},
beforeSend: function (xhr) {
alertSpan.removeClass().addClass("loading");
},
success: function (result, status, xhr) {
alertSpan.removeClass().addClass("success");
},
error: function (jqXhr, textStatus, errorThrown) {
alertSpan.removeClass().addClass("error");
}
});
});
And on the controller side, I Deserialized string json as: Just showing partial code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FtpCreateAndOrSync(string xmlNodes)
{
//Deserializing nodes
var xmlNodesModels = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<IEnumerable<XmlNode>>(
xmlNodes).ToArray();
////Alternative
//var data = JsonConvert.DeserializeObject<IEnumerable<XmlNode>>(xmlNodes);
return Json(new { cr = createResult, dr = dbResult });
}
Hope this helps someone.

AngularJS Services (Update/Save)

New to AngularJS and trying to get a grasp of the framework, and trying to build a basic CRUD app. I can't seem to figure out what is needed to Update an existing record. Here is my service:
angular.module('appServices', ['ngResource']).
factory('App', function ($resource) {
var Item = $resource('App/:AppId', {
//Default parameters
AppId: '#id'
}, {
//Actions
query: {
method: 'GET',
isArray: true
},
getById: {
method: 'PUT'
},
update: {
method: 'POST'
}
});
return Item;
});
I can run a basic Get all query, and getById to populate an edit form, but that's where I'm stuck. Here is example code for getById
$scope.apps = App.query();
$scope.getEdit = function(AppId) {
App.getById({id:AppId}, function(app) {
$scope.original = app;
$scope.app = new App(app);
});
};
$scope.save = function() {
//What type of information should go here?
//Do I need to make changes to the appServices?
};
I guess, I'm just not sure what's next concerning Updating existing information, or how the "app" object gets passed to the API, can anyone point me in the right direction, or show me a quick update method?
This is a really messy way of handling save operations in angular. For one - you should not be using PUT operations for retrieval requests and secondly - all of this is already built-in to angular. See below.
var Item = $resource( 'App/Details/:AppId', { AppId: '#id' } );
var item = Item.get({ id: 1 }, function( data ) {
data.setAnothervalue = 'fake value';
data.$save();
);
What I'm doing here is retrieving an "Item" and then immediately saving it with new data once it's returned.
Angular JS provides a stack of defaults already, including query, save, remove/delete, get.etc. And for most RESTful APIs, you really shouldn't need to add much, if anything at all. See the resource docs for more information, particularly the information on defaults: http://docs.angularjs.org/api/ngResource.$resource
Additionally, once you get a handle on that - you may want to use $save for both create/update operations, but using POST/PUT (RESTful conventions). If you do, see my article that I wrote about not too long ago: http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/
After doing a bit more research, and reviewing Daniel's link (thanks). I got it working.
Controller method:
$scope.save = function() {
$scope.app.update();
};
Service Factory:
var Item = $resource('App/Details/:AppId', {
//Default parameters
AppId: '#id'
}, {
//Actions
query: {
method: 'GET',
isArray: true
},
getById: {
method: 'PUT'
},
update: {
method: 'POST'
}
});
Item.prototype.update = function (cb) {
console.log(this.AppId);
return Item.update({ AppId: this.AppId },
angular.extend({}, this, { AppId: undefined }), cb);
};
return Item;

is it possible to include an event in a javascript function?

i was just wondering if getting a jqgrid event from a main javascript and separate it using another javascript in a form of function would work? what im trying to do is like this. i have a code :
...//some code here
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $('#eSessionID3').val(),
'dataType': 'data',
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
...//some code here
}
else
{
...//some code here
}
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('errmsg');
},
...//some code here
i want to get this code and write this in another javascript file and make this as a function, so that my other file could use this one..is it possible?
i created something like this in my other javascrtip file where i planned to put all my functions. here's the code (functions.js):
function serialLoad(){
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $('#eSessionID3').val(),
'dataType': 'data',
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
...//some code here
}
else
{
...//some code here
}
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('errmsg');
}
}
this isn't working and display a message syntax error. i don't know how to correct this. is there anyone who can help me.?
First of all the answer on your derect question. If you define in the functions.js file some global variable, for example, myGlobal:
myGlobal = {};
myGlobal = serializeGridData: function(postData) {
// ... here is the implementation
};
you can use it in another JavaScript file which must be included after the functions.js file:
serializeGridData: myGlobal.serializeGridData
(just use such parameter in the jqGrid definition).
If you want to use the serializeGridData parameter with the value in the most of your jqGrids you can overwrite the default value of serializeGridData in the functions.js file instead:
jQuery.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
// ... here is the implementation
},
loadError: function(xhr, msg, e) {
showMessage('errmsg');
}
});
In the example I ovewride additionally default datatype: 'xml' jqGrid parameter to datatype: 'json'. It shows that in the way you can set default values of any jqGrid parameter.
What it seems to me you really need is to use prmNames jqGrid parameter to rename some defaulf names of the standard jqGrid parameters. For example with
prmNames: {
rows:"recordLimit",
sort: "sort_fields",
search:null,
nd:null
}
you rename the standard rows parameter to recordLimit, the sidx to sort_fields and remove _search and nd parameters to be send.
Additionally you can use postData having some properties defined as the function (see here for details). For example:
postData: {
SessionID: function() {
return $('#eSessionID3').val();
},
rowDataAsObjects: false,
queryRowCount: true,
dataType: 'data',
recordOffset: function() {
var pd = jQuery("#list2")[0].p.postData;
return pd.recordLimit * (pd.page - 1);
},
json: function() {
var pd = jQuery("#list2")[0].p.postData;
return {
SessionID: $('#eSessionID3').val(),
dataType: 'data',
recordOffset: pd.recordLimit * (pd.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_fields: pd.sort_fields
};
}
}
I used here both json parameter which you currently use and add parameters like SessionID, queryRowCount and so on directly in the list of parameters which will be send. Of course it is enough to send only one way (either json or the rest) to send the aditional information which you need.
The second example is incorrect, as you are declaring a javascript object as the body of a function, what you could do is:
function serialLoad() {
// Return an object with the required members
return {
serializeGridData: function(postData) { ... },
loadError: function(xhr, msg, e) { ... }
};
}
You are mixing function declaration and object literal notation. This syntax: property: value is used when creating an object with object literal notation:
var obj = {
prop: val,
prop2: val
};
serializeGridData and loadError are properties of some object and you cannot define those by just putting them into a function.
One way would be to create two functions, one for serializeGridData and one for loadError, e.g.
function serialLoad(postData){
var jsonParams = {
//...
};
if (postData.sord == 'desc') {
//... some code here
}
else {
//... some code here
}
return 'json=' + jsonParams;
}
function onError(xhr, msg, e) {
showMessage('errmsg');
}
Then you can assign them in your other file to the object:
// ... some code here
serializeGridData: serialLoad,
loadError: onError,
//... some code here
Another way is to pass the object in question to the function and assign the properties there:
function attachLoadHandler(obj) {
obj.serializeGridData = function(postData) {
//...
};
obj.loadError = function(xhr, msg, e) {
//...
};
}
Then you have to pass the object you created to that function:
attachLoadHandler(obj);
But I think the first approach is easier to understand.

Categories

Resources