JavaScript Object storage and usage via sessionStorage - javascript

var obj = {
conn : null,
first : function(thisIdentity) {
"use strict";
var myObj = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
myObj.conn = new Connection(data.user_id, "127.0.0.1:80");
sessionStorage.setItem('connection', JSON.stringify(myObj.conn));
}
});
},
second : function(thisIdentity) {
"use strict";
var myObj = this;
var conntn = sessionStorage.getItem('connection');
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
var parsedConnection = JSON.parse(conntn);
parsedConnection.sendMsg(data.id, data.nid);
}
});
}
};
var Connection = (function() {
function Connection(uid, url) {
this.uid = uid;
this.open = false;
this.socket = new WebSocket("ws://"+url);
this.setupConnectionEvents();
},
sendMsg : function(id, nid) {
alert("Working");
},
// other functions
})();
Now basically an object is assigned to conn variable in AJAX callback function of first function and I am storing the object via sessionStorage and retrieving the object in the second function and using it in the AJAX callback but when I call the method via parsedConnection.sendMsg(data.id, data.nid); it is throwing an error that
TypeError: parsedConnection.sendMsg is not a function
I did use console.log(parsedConnection); and it shows that object is there with proper values. I just want to know how to retrieve the object and call the method on it in AJAX callback function of second. Thanks!

Related

Assign and use javascript object property via AJAX

So I have this Javascript object :
var obj = {
conn : null,
first : function(thisIdentity) {
"use strict";
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
this.conn = new Connection(data.user_id, "127.0.0.1:80");
}
});
},
second : function(thisIdentity) {
"use strict";
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
// using this.conn now results in UNDEFINED
}
});
}
};
Now basically value is assigned to conn variable in AJAX call of first function but when I try to use the same value in second function then it states this.conn is undefined. I just want to know how to assign value to the object's property and keep it preserved for future use? Thanks!
In the ajax success callback the this refers to a different scope than the original object.
Change you code to this:
var obj = {
conn : null,
first : function(thisIdentity) {
"use strict";
var mySelf = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
mySelf.conn = new Connection(data.user_id, "127.0.0.1:80");
}
});
},
second : function(thisIdentity) {
"use strict";
var mySelf = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
// now you can access the connection with mySelf.conn
}
});
}
};
The syntax itself is wrong. You are creating a variable or giving an expression inside an object literal. Remember this is not a function, but instead, it should be:
$.ajax ({
// computation and in success function
conn: new Connection(data.user_id, "127.0.0.1:80")
});
Updated
When you are giving such a way of definition:
success : function() {
this.conn = new Connection(data.user_id, "127.0.0.1:80");
}
Here, the this object refers to the success function and not your object. Read Understanding Scope and Context in JavaScript. Now you need to create a proxy variable for this and use it:
first : function(thisIdentity) {
"use strict";
var myObj = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
myObj.conn = new Connection(data.user_id, "127.0.0.1:80");
}
});
},

method with parameter in unknown js function issues

I'm trying to protect a part of my js code wrapping my code with an Unknown function.
I have edit my function to change
function banana(url) {}
to method
banana: function(url){ },
when I try to call my function banana in another function i try to use
this.banana(url);
but i have this error:
TypeError: this.banana is not a function
Full code:
(function (){
var url_test = "./add_user.php?opt=get_user&token=<?php echo $token; ?>";
if (typeof $.customfnc == 'undefined')
$.customfnc = {}
$.customfnc.get = {
setup: function (){
var url = "google.ca";
this.banana(url);
},
banana: function (url){
console.log("my url: " + url);
};
};
};
// on ready render data
$(document).ready(function() {
$.customfnc.get.setup();
});
})(jQuery);
thanks for your help!
The issue here is that the scope of 'this' is not exactly what you might think it is.
The way I have handled this particular issue in the past is to add
var self = this;
Outside of the object that is attempting to self reference. This may impact how you have set up youre .get() object though.
$.customfnc.get = function(){
var self = this;
self.setup = function (){
//....
self.banana(URL)
}
self.banana = function(url){
//...
}
}

sending parameters to self invoking functions

How do I send parameters to self invoking functions. like following code.
MyNameSpace.Administration.WebAdministrator = function () {
var init = function () {
//some code here
},
CreateSubSite = function (id, url) {
//some code here
}
return {
start: function () {
init();
},
createSubSite: CreateSubSite(myId, myUrl)
}();
$(document).ready(function () {
MyNameSpace.Administration.WebAdministrator.start();
$("div.large-app").on("click", "#btnCreate", function () {
var id = "something";
var url = "something";
MyNameSpace.Administration.WebAdministrator.createSubSite(id, url);
});
});
When I add this code on my js file and run the web application it says myId and myUrl not defind and not runing the js code.
Looks like you're really trying to do this
var MyNameSpace = {
Administration : {
WebAdministrator : {
init : function () {
//some code here
},
CreateSubSite : function (id, url) {
//some code here
},
start : function () {
this.init(); // really ?
}
}
}
};
$(document).ready(function () {
MyNameSpace.Administration.WebAdministrator.start();
$("div.large-app").on("click", "#btnCreate", function () {
var id = "something";
var url = "something";
MyNameSpace.Administration.WebAdministrator.CreateSubSite(id, url);
});
});
FIDDLE

How do I use a constructor in javascript

Here is my problem.
I am using Backbone js and every collection I have defined requires the same check on save or destroy. Except that the destroy success functions need to be passed an element to remove from the page when the destroy succeeds.
I didn't want to copy and paste the same code into every save or destroy method so I created this:
window.SAVE_TYPE_DESTROY = 'destroy';
window.SaveResponseHandler = function(el,type){
if (!type){
this.success = function() {
this._success();
};
}else if (type == window.SAVE_TYPE_DESTROY){
this.success = function() {
this._success();
$(el).remove();
};
}
};
SaveResponseHandler.prototype._success = function(model, response, options) {
if ((response.success * 1) === 0) {
persistError(model, {
responseText: response.message
}, {});
}
};
SaveResponseHandler.prototype.error = persistError;
var saveResponseHandler = new SaveResponseHandler();
And I use it like this:
destroy: function() {
var el = this.el;
var model = this.model;
this.model.destroy(new SaveResponseHandler(el,'destroy'));
},
change: function() {
this.model.set({
job_category_name: $($(this.el).find('input')[0]).val()
});
var viewView = this.viewView;
this.model.save(null, saveResponseHandler);
}
The problem is when success is called I get the following error:
Uncaught TypeError: Object [object Window] has no method '_success'
Any help will be much appreciated. I'm also open to any suggestions on better ways to handle this.
this inside of SaveResponseHandler.success isn't SaveResponseHandler, it's window.
window.SaveResponseHandler = function(el, type) {
var self = this;
if (!type) {
this.success = function() {
self._success();
};
} else if (type == window.SAVE_TYPE_DESTROY) {
this.success = function() {
self._success();
$(el).remove();
};
}
};
http://jsfiddle.net/ethagnawl/VmM5z/

Resolve function pointer in $(document).ready(function(){}); by json string name

I have a json object retrieved from server in my $(document).ready(...); that has an string that I would like to resolve to a function also defined within $(document).ready(...); so, for example:
$(document).ready(function{
$.getJSON(/*blah*/,function(data){/*more blah*/});
function doAdd(left,right) {
return left+right;
}
function doSub(left,right) {
return left-right;
}
});
with json string:
{"doAdd":{"left":10,"right":20}}
One way I thought about was creating an associative array of the function before loading the json:
var assocArray=...;
assocArray['doAdd'] = doAdd;
assocArray['doSub'] = doSub;
Using eval or window[](); are no good as the function may not be called for some time, basically I want to link/resolve but not execute yet.
Change your JSON to
{method: "doAdd", parameters : {"left":10,"right":20}}
Then do
var method = eval(json.method);
// This doesn't call it. Just gets the pointer
Or (haven't tried this)
var method = this[json.method]
How about something like this?
$(function(){
// Function to be called at later date
var ressolvedFunc = null;
// Ajax call
$.getJSON(/*blah*/,function(data){
// Generate one function from another
ressolvedFunc = (function(data) {
var innerFunc;
var left = data.left;
var right = data.right;
// Detect action
for (action in data) {
if (action == "doAdd")
innerFunc = function() {
return left + right;
};
else
innerFunc = function() {
return left - right;
};
}
return innerFunc;
})(data);
});
});
The anonymous function returns fresh function, with the new values stored within the enclosure. This should allow you to call the function at later date with the data previously retrieved from the GET request.
Rich
try this:
var doX = (function() {
var
data = [],
getDo = function(action) {
for(var d in data) {
if (data[d][action]) {
return data[d];
}
}
return null;
};
return {
set: function(sdata) {
data.push(sdata);
},
doAdd: function() {
var add = getDo("doAdd");
if (!add)
return 0;
return add.doAdd.left + add.doAdd.right;
},
doSub: function() {
var sub = getDo("doSub");
if (!sub)
return 0;
return sub.doAdd.left + sub.doAdd.right;
}
};
})();
$(document).ready(function{
$.getJSON(/*blah*/,function(data){ doX.set(data); });
});

Categories