js function for multiple variables - javascript

So, I have two js variables that i use a lot:
var rhpp = jQuery(this).parents('.rhp');
var rhp_id = rhpp.data("pi");
For example:
function my_function_1 (){
jQuery(document).on('click', '.button_1', function (e) {
var rhpp_1= jQuery(this).parents('.rhp');
var rhp_id_1 = rhpp_1.data("pi");
//do something
});
}
function my_function_2 (){
jQuery(document).on('click', '.button_2', function (e) {
var rhpp_2 = jQuery(this).parents('.rhp');
var rhp_id_2 = rhpp_2.data("pi");
//do something
});
}
function my_function_3 (){
jQuery(document).on('click', '.button_3', function (e) {
var rhpp_3 = jQuery(this).parents('.rhp');
var rhp_id_3 = rhpp_3.data("pi");
//do something
});
}
Because of it, i want to make this into a function that I can reuse:
function RHP_PARENT(a, b) {
var a = jQuery(this).parents('.rhp');
var b = a.data("pi");
}
Then, RHP_PARENT("rhpp", "rhp_id");
of course, it is not right. I am not too familiar with how to make a function for variables.
Could someone show me?
Thanks!

You could create a function which returns both of those values.
function getRhpParent(element) {
var rhpp = jQuery(element).parents('.rhp');
return {
rhpp: rhpp,
rhpp_id: rhpp.data("pi")
};
}
// Usage
var temp = getRhpParent(this);
var rhpp = temp.rhpp;
var rhp_id = temp.rhp_id;

You could do something like this:
function RHP_PARENT(that) {
var a = jQuery(that).parents('.rhp');
var b = a.data("pi");
return { parents: a, data: b };
}
This allows you to write:
var rhp_id_1 = RHP_PARENT(this).data;

Do you intend to access those variables outside of RHP_PARENT?
If so you should instantiate a and b outside of the function.
Do you intend to access a and b as properties of RHP_PARENT?
In which case, you may want to do the following:
var RHP_PARENT = {
'a': (function(){
jQuery(this).parents('.rhp');
})(),
'b': (function(){
this.a.data("pi");
})()
}
It's not entirely clear based on your question what your use case is, so it's difficult to formulate a single answer.
EDIT:
It seems like you updated your question, here are two viable solutions to your problem.
The following code will loop over all elements which have classes that begin with "button". This solves for the homogenous use case:
$("[class^='button']").each(function(){
$(this).click(function (e) {
var rhpp = jQuery(this).parents('.rhp');
var rhp_id = rhpp.data("pi");
//do something
});
})
The following solution solves for a more general use case and is a bit more flexible. The advantage here is that the business logic for getting rhhp and rhp_id is broken out into helper functions, allowing it to be more reusable. You may also reference other functions within the same object by using this:
var my_functions = {
get_rhhp: function(el){
return jQuery(el).parents('.rhp');
},
get_rhp_id: function(rhhp){
return rhhp.data("pi");
},
"my_function_1": function(){
jQuery(document).on('click', '.button_1', function (e) {
var rhhp = get_rhhp();
var rhp_id = get_rhp_id(rhhp);
//do something
});
},
"my_function_2": function(){
jQuery(document).on('click', '.button_2', function (e) {
var rhhp = get_rhhp();
var rhp_id = get_rhp_id(rhhp);
//do something
});
},
"my_function_3": function(){
jQuery(document).on('click', '.button_3', function (e) {
var rhhp = get_rhhp();
var rhp_id = get_rhp_id(rhhp);
//do something
});
}
}

Related

JavaScript uncaught type error illegal invocation

var Rules = Rules || (function () {
saverule = function () {
var level = document.getElementById("level-selection");
var metrics = document.getElementById("metric-selection");
var operator = document.getElementById("operator-selection");
var value = document.getElementById("value123");
var saveAction = $("#hidden-save").val();
$.post(saveAction, { level_id: level, product_id: metrics, opp: operator, value: value }, function () {
},
'json');
};
wireLinkActions = function () {
$("a.save-ok").on("click", function(event) {
saverule();
return false;
});
};
return {
Initialize: function () {
wireLinkActions();
}
}
})();
$(document).ready(Rules.Initialize);
illegal invocation error it wont even cal the the save rule function while debugging also
Make sure your return the values and not the DOM element itself.
For example change this:
var level = document.getElementById("level-selection");
into this:
var level = document.getElementById("level-selection").value;
or, simply use jQuery such as this:
var level = $("#level-selection").val();

OOJS call other method

var Lines = function(startXCon, endXCon,startYCon, endYCon)
{
this.drawCurve = function()
{
}
this.changeCurve = function(e)
{
//how can I call drawCurve from this method
}
}
The comment in my code explains the problem. Is this possible or are all methods private?
Like this:
var Lines = function(startXCon, endXCon,startYCon, endYCon){
var self = this; // store this as a variable to use in nested function
this.drawCurve = function(){}
this.changeCurve = function(e){
self.drawCurve(); //now call this.drawCurve()
}
}

call javascript function after another

Can you please help answering this. Please not the contraints.
var myLib = {
var callback_one = function (result_from_web_service) {
console.log('callback_one');
};
var callback_one = function (result_from_web_service) {
console.log('callback_two');
};
var init = function () {
console.log('initializing...');
async_call_one(callback_one);
async_call_two(callback_two);
};
var doStuff = function () {
console.log('doStuff is called');
};
};
// User of my library
myLib.init();
myLib.doStuff();
// output
initializing...
doStuff is called
callback_one
callback_two
// What i need:
initializing...
callback_one
callback_two
doStuff is called
Constraint:
calling myLib.init shall not end up calling myLib.doStuff. i.e. myLib.init should be independent of myLib.doStuff
myLib.doStuff() should be called after myLib.init() and its callbacks are returned.
Thanks,
//You must change your API so init is async
//There is no way to have it wait until all initialization is done before it retuns
var init = function (initDone) {
console.log('initializing...');
var n = 0;
function serviceDone(){
n++;
if(n >= 2){ initDone() }
}
async_call_one(function(x){ callback_one(x); serviceDone() });
async_call_two(function(x){ callback_two(x); serviceDone() });
};
// User of my library
myLib.init(function(){
myLib.doStuff();
})
The way I parallelized those calls is very ad-hoc s not the most maintainable (there I need to keep the calls to serviceDone and the value of N in sync).. In the long run I would recommend using one of the many JS async programming libs out there.
hugomg has a good answer.
Yet I think it is really specific and could benefit a sort of workflow implementation, like this (approximately...):
function void() {}
var myLib = {
var g_flow = [];
g_flow[this.init] = [];
g_flow[this.init]["whendone"] = this.callback_one;
g_flow[this.init]["done"] = false;
g_flow[this.callback_one] = [];
g_flow[this.callback_one]["whendone"] = this.callback_two;
g_flow[this.callback_one]["done"] = false;
g_flow[this.callback_two] = [];
g_flow[this.callback_two]["whendone"] = this.doStuff;
g_flow[this.callback_two]["done"] = false;
g_flow[this.doStuff] = [];
g_flow[this.doStuff]["whendone"] = void;
g_flow[this.doStuff]["done"] = false;
var callback_one = function (result_from_web_service) {
console.log('callback_one');
};
var callback_one = function (result_from_web_service) {
console.log('callback_two');
};
var init = function () {
console.log('initializing...');
};
var doStuff = function () {
console.log('doStuff is called');
};
var flow_onward(hwnd) {
async_call(function(){ hwnd(); myLib.flow_onward(g_flow[hwnd]["whendone"]); });
}
flow_onward(this.init);
};
// User of my library
myLib.init();
myLib.doStuff();
Doing this way you can ensure the sequentiality and expand the numbers of callback as much as you want.
ps: this code has not been tested

Issue while defining jQuery functions

Trying to define a couple of functions like so:
user = (function() {
var friends_list = (function() {
$.get('/ajax/user/friends_list', function(data) {
......
So I can later on call them when need it like so user.friends_list() but for now, the only thing I get is this following error:
TypeError: Object function () {
var friends_list = (function() {
$.get(....
I just don't know where else to look, any suggestions?
You need to create user as an object, in your case the friends_list is a closure method, it will be availble outside the function
user = {
friends_list : function(){
....
}
}
make a user object and not function
var user = {
friends_list : function(){
$.get('/ajax/user/friends_list', function(data) {
......
}
}
and call it like.. user.friends_list()
fiddle here
You're using a closure here, so friend_list is invisible on the outside of user.
If you want to use closures, to hide some variables, to best way to export friend_list would be:
(function(){
var somePrivateVariable;
window.user = {};
window.user.friend_list = function() {
// make use of somePrivateVariable...
};
})();
user = function() {
this.friends_list = function() {
$.get('/ajax/user/friends_list', function(data) {
......
});
};
return this;
};
Above should also work.
reference http://www.w3schools.com/js/js_objects.asp
You can check out this link
Here is the code:
var global = {};
global.sayHello = function (x){
//do your code here
console.log('Hello ' + x );
};
global.sayHello('Kevin');
user = new function(){
var private_variable;
function private_method(){}
this.global_variable = '';
this.global_method = function(){};
}

JavaScript: Accessing Nested Objects

The code looks like this
function Scripts() {this.FindById = function (id) {
this.FindById.constructor.prototype.value = function () {
return document.getElementById(id).value;
}}}
var Control = new Scripts();
Now when i say Control.FindById("T1").value(). I am not able to get the textInput("T1")'s value.
It seems that your code is a bit more complicated then it should be ;-)
Personally I would write it this way (not tested):
function Scripts() {
this.findById = function(id) {
var el = document.getElementById(id);
return {
value: function() {
return el.value;
}
}
}
}
The findById() now closes over a node and returns an interface that can return its value.
Also, your idea sounds a lot like Singleton, so you wouldn't even need the extra Scripts constructor:
var Control = {
findById: function(id) {
var el = document.getElementById(id);
return {
value: function() {
return el.value;
}
}
}
}
Working example: http://jsfiddle.net/YYkD7/
Try this:
function Scripts() {this.FindById = function (id) {
this.FindById.constructor.prototype.value = function () {
return document.getElementById(id).value
}}}
You didn't close the last "}" :-)

Categories