sending parameters to self invoking functions - javascript

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

Related

How can I extend a JS Component?

I have this custom component
(function ($) {
$.fn.stuff = function (options) {
var myStuff = this;
myStuff.render_item = function () {
// Do something
return "default result";
};
myStuff.test = function () {
myStuff.render_item;
};
return myStuff;
};
}(jQuery));
I want to "extend" this component and re-declare the "render_item" fonction without editing the file directly since it's from a library.
How can I achieve this ?
Thank you.
You can monkey-patch it like this:
(function($) {
$.fn.old_stuff = $.fn.stuff;
$.fn.stuff = function(options) {
var myStuff = $(this).old_stuff(options);
myStuff.old_render_item = myStuff.render_item;
myStuff.render_item = function() {
// do something
myStuff.old_render_item();
// do something else
};
return myStuff;
};
}(jQuery));

JavaScript Object storage and usage via sessionStorage

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!

Create a function / event for user in Javascript prototype

I have a Protoype in my project as follows:
(function($) {
$.fn.observerPages = function(pageNo) {
return new ObserverPage($(this), pageNo);
};
function ObserverPage(Parent, pageNo) {
try {
this.parent = Parent;
this.isInitialized = false;
this.timer = -1;
this.highChart = [];
} catch (e) {
}
}
ObserverPage.prototype = {
initialize: function(url) {
isInitialized = true;
},
update: function(controllerurl) {
if (isInitialized == true) {
//Update
}
},
startTimer: function(url, interval) {},
stopTimer: function() {}
};
})(jQuery);
This initiates a page that is hooked with an observer and gets data from an ajax service at a defined interval.
What I require is to put an event in this where the user can put a function when this.isInitialized becomes true.
Currently I am using it like this.
var page = $("liveDiv").observerPages(2);
page.initialize("http://localhost:5549/GetLatestNews");
page.update("http://localhost:5549/GetLatestNewsData");
I want an event that the user can handle when isInitialized gets true and can be used like this
page.onInitialize(function(){
//User writes his function
});
How can I do that?
Solution might be similar to this:
var event = new Event('pageinit');
ObserverPage.prototype = {
initialize: function(url) {
isInitialized = true;
},
update: function(controllerurl) {
if (isInitialized == true) {
document.dispatchEvent(event);
}
},
startTimer: function(url, interval) {},
stopTimer: function() {},
onInitialize: function(callback)
{
document.addEventListener('pageinit', callback, false);
}
};
EDIT: this->document

call function before plugin function starts

I have a function to find highest value in an XML file from certain tag which has to assign one of default value in plugin. My problem is my plugin code runs before the other function hence a null value is returned. Can I run function get_Highest_Property_Prise() before plugin, like java constructor? Or some how initialize a global variable before plugin code kicks in?
var pulgin_Global_Variables = {
hight_price: ""
};
(function($) {
$.fn.SearchProperty = function (options) {
var defaults = {
S_MinPrice: 0,
S_MaxPrice: get_Highest_Property_Prise()
};
alert("yo yo "+defaults.S_MaxPrice);
}
})(jQuery);
function get_Highest_Property_Prise()
{
$.get('Data.xml', function (XML_property) {
$(XML_property).find('property').each(function () {
var c_Price = parseInt($(this).find('priceask').text().replace(',', ''));
if (c_Price > pulgin_Global_Variables.hight_price) {
pulgin_Global_Variables.hight_price = c_Price;
}
}); //end of function
});
}
var pulgin_Global_Variables = {
hight_price: ""
};
$.fn.SearchProperty = function (options) {
var defaults = {
S_MinPrice: 0,
S_MaxPrice: pulgin_Global_Variables.hight_price
};
alert("yo yo "+defaults.S_MaxPrice);
}
})(jQuery);
//here set max price to match your global object
$.get('Data.xml', function (XML_property) {
$(XML_property).find('property').each(function () {
var c_Price = parseInt($(this).find('priceask').text().replace(',', ''));
if (c_Price > pulgin_Global_Variables.hight_price) {
pulgin_Global_Variables.hight_price = c_Price;
}
}); //end of function
}).done(function () {
$(whatever).SearchProperty()
})

JavaScript refer to a method inside a method?

Ok, just solved one problem where this refered to the wrong scope. Now I have another problem.
So I want to call a method that is inside a method. But I do not know how, check this source:
function someObj() {
var self = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
self.someMethod2.methodMethod();
//I want this.someMethod2.methodMethod() to be called
//...but I get an big error instead. Is it even possible?
//this.someMethod2() works fine.
};
};
this.someMethod2 = function() {
this.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
alert('NO, NOT THIS!');
};
}
Error msg:
Uncaught TypeError: Object function () { ...
With your code, someMethod2 would need to execute first for the function expression to be assigned. Even then, it would be assigned to the parent instance.
Bearing in mind that all functions are objects in JavaScript, this is what you want instead:
this.someMethod2 = function() {
alert('NO, NOT THIS!');
};
this.someMethod2.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
You are trying to use an object accessor on a function. If you want it to work in this way, you need to return an object literal from your call to the "outer" function.
this.someMethod2 = function() {
return {
methodMethod: function() {
alert('THIS IS THE ONE I WANTED!');
}
}
};
You can then chain the call. self.someMethod2().methodMethod();
While this is not directly possible, you can pass a "command" to the outer function to tell it to execute the inner function. But, are you sure this is what you really need? Perhaps you should use objects instead of functions here. But here's the "command" way:
this.someMethod2 = function(cmd) {
var methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
if (cmd === "methodMethod") {
methodMethod();
return;
}
alert('NO, NOT THIS!');
};
function someObj() {
var self = this;
this.someMethod1 = function () {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function () {
self.someMethod2().methodMethod();
};
};
this.someMethod2 = function () {
this.methodMethod = function () {
alert('THIS IS THE ONE I WANTED!');
};
//return this for chain method.
return this;
};
}
trying
function someObj() {
var self = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
self.someMethod2().methodMethod();
};
this.someMethod2 = function() {
this.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
alert('NO, NOT THIS!');
return this;
};
}
Also if you use prototype then
function someObj() {
var self = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
self.someMethod2.methodMethod();//['methodMethod']();
};
};
this.someMethod2 = function() {
};
this.someMethod2.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
};
But the method methodMethod is static

Categories