passing $(this) from function to function - javascript

I have 2 different event on different classes :
$('.box1').click(function(){
$(this).find('something').css('red')
}
$('#otherId .box2').change(function(){
$(this).find('something').css('red')
}
But I plan to split them out to a function to avoid duplicate code
function getDetails(this){
this.find(".something").css('red');
}
but how to call the function later? pass the $(this) to the function?
$('#otherId .box2').change(function(){
getDetails($(this))
}

this is a keyword so it can't be a param name
function getDetails(el) {
el.find(".something").css('red');
}
$('#otherId .box2').change(function () {
getDetails($(this))
})

The keyword this can't be used as an argument, but you can keep using this within the function body:
function getDetails()
{
$(this).find(".something").css('red');
}
And then call it like so:
$('#otherId .box2').change(function() {
getDetails.call(this);
}
See also: Function.call()

You can use something like this to pass it through if you want to get an inputs value then change it and output the final value next to it:
var finalOutput;
function getDetails(args) {
args = "Hello World";
return args;
}
$('.box2').change(function(){
var inputValue = $(this).val();
finalOutput = getDetails(inputValue);
$('.box2').after('<b>' + finalOutput + '</b>');
});
Here is a working example:
http://jsfiddle.net/La4v9mL0/

Related

Javascript return variables from each function

Looping through children elements using each.
var divHeights = [];
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
alert(divHeights); // fails
How can I return the divHeights variable?
I've tried
var hts = ('#parent').children('div').each(function () { ...
but obviously that won't work.
You can do this in better way using .map() like:-
var divHeights = $('#parent').children('div').map(function () {
return this.clientHeight || 0;
}).get();
DEMO FIDDLE
The divHeights variable is available all the time. You can just assign it to a variable whenever you want:
var hts = divHeights;
This will just be another reference to the array, so you can do that any time after the array is created, even before you have put any values into it:
var divHeights = [];
var hts = divHeights;
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
You can of couse just use the variable divHeights instead of the variable hts when you want to use the result, or just use the variable hts instead of divHeights from start.
You could make it into a function like this:
function getHeights() {
return $('#parent div').map(function() {
return this.clientHeight;
});
}
Then you can just call the function wherever you like to get the array contents.

JS/ use object which define outside the function

I have the next function in JS:
function status(){
this.functionA = function(){}
//Some others function and fields
}
and I have another function:
function create(root){
var server = libary(function (port) {
//Here some functions
});
var returnValue = {
current:status(),
cur:function(port){
current.functionA();
}}
return returnValue;
}
when I call current.functionA(), It says that current is undefined. How can I call functionA()?
When you have a function-constructor like status(), you'll need to call new for it. I've revised part of your code here.
var returnValue = {
current: new status(),
cur:function(port){
current.functionA();
}}
return returnValue;
}
Just to differentiate; create() doesn't need a new statement because you're actually creating and returning an object to refer to, inside of the function.
function status(){
this.functionA = function(){alert("functionA");}
}
function create(root){
var returnValue = {
current:status.call(returnValue),
cur:function(port){ this.functionA(); }.bind(returnValue)
}
return returnValue;
}
create().cur(999);
I corrected your issue using the JavaScript "call" and "bind" methods which are part of the Function prototype.

Expose knockout ViewMode from function to another function

I have next situation...
For some reasons I need to bind knockout ViewModel inside function and call it on specific terms.
this is my code:
if (... some conditions ...) {
var polugodiste = $("#polugodiste").val();
ApplyBindingsIzostanak(polugodiste);
$('#flip-min').change(function () {
IzostanakViewModel.selectedPolugodiste(parseInt($(this).val()));
IzostanakViewModel.GetIzostanci();
});
}
and function:
function ApplyBindingsIzostanak(polugodiste)
{
var Izostanak = function (cas, tekst) {
this.Cas = cas;
this.Tekst = tekst;
};
var IzostanakViewModel = {
selectedStatus: ko.observable(),
selectedPolugodiste: ko.observable(polugodiste),
ucenikIzostanakList: ko.observableArray([]),
GetIzostanci: function () {
.. do some code ...
}
};
ko.applyBindings(IzostanakViewModel);
}
Binding is working, but I get error when I try calling IzostanakViewModel inside my if, it says IzostanakViewModel is not defined.
Can I and how expose IzostanakViewModel from function and use it inside if statement?
NOTE*
I could try something like this:
add this code to ApplyBindingsIzostanak():
window.foo = function() {
IzostanakViewMode.GetIzostanci();
}
and then call it from if statement, but maybe there is better solution...
IzostanakViewModel is a variable within the ApplyBindingsIzostanak() function. Why don't you just return it so you have a reference to it?
function ApplyBindingsIzostanak(polugodiste)
// ...
return IzostanakViewModel;
}
var IzostanakViewModel = ApplyBindingsIzostanak(polugodiste);
$('#flip-min').change(function () {
IzostanakViewModel.selectedPolugodiste(parseInt($(this).val()));
IzostanakViewModel.GetIzostanci();
});

Giving data/params with my function jquery

var regfbnaam = $('#regfbnaam');
$('#regnaam').focusin({param1: regfbnaam},removeClass);
function removeClass(e)
{
param1.removeClass('hidden');
}
Error in console.log: param1 is nog defined. Means he doesn't get the value of my param1. What am i doing wrong here?
(trying to get a variable with a onclick event to my function)
Try this (tested)
function removeClass(e) {
var param1 = e.data.param1;
param1.removeClass('hidden');
}
jQuery(document).ready(function($) {
var regfbnaam = $('#regfbnaam');
$('#regnaam').focusin({param1: regfbnaam},removeClass);
});
Reference:
event.data
.focusin()
Try:
function removeClass(e)
{
$(e.data.param1).removeClass('hidden');
}
Not exactly sure what you trying to do with that syntax. I would suggest a different approach:
var $el = $(el);
$el.on('focusin', function(){
removeClass(e, {param1: regfbnaam});
});
function removeClass(e, params)
{
params.param1.removeClass('hidden');
}
Untested, but I think it should work. Basically the idea is that you are binding a function to the element and then providing it with whatever arguments it needs.

How to pass a string value as a reference in javascript and change it over there

How can I pass a string value by reference in javascript.
I want this kind of functionality.
//Library.js
function TryAppend(strMain,value)
{
strMain=strMain+value;
return true;
}
//pager.aspx
function validate()
{
str="Checking";
TryAppend(str,"TextBox");
alert(str); //expected result "Checking" TextBox
//result being obtained "Checking"
}
How to do this. ?
You cannot pass a value by reference in JS. You could create an object with a function to do this for you:
function TryAppend(originalValue) {
// Holds the value to return
this.Value = originalValue;
// The function joins the two strings
this.Append = function (append) {
this.Value+=append;
return true;
}
}
You can then use this in any method as follows:
function AnyProcedure() {
var str = "Checking";
var append = new TryAppend(str);
if (append.Append("TextBox")) {
alert(append.Value); // Will give "CheckingTextBox"
}
}
Each time you call append, the Value string will be appended to. I.e.
If you then did:
append.Append(" Foo");
append.Value would equal CheckingTextBox Foo.
You need to return the String instead of true !!
function TryAppend(strMain,value) {
strMain=strMain+value;
return strMain; //you need return the 'String Value' to use in it another method
}
//pager.aspx
function validate() {
str="Checking";
str = TryAppend(str,"TextBox");
alert(str); //expected result "Checking" TextBox
//result being obtained "Checking"
}
Create a global variable (say gblstrMain) outside the function TryAppend and then set its value to strMain inside the function.
var gblstrMain;
function TryAppend(strMain,value)
{
strMain=strMain+value;
gblstrMain = strMain;
return true;
}
//pager.aspx
function validate()
{
str="Checking";
TryAppend(str,"TextBox");
str = gblstrMain;
alert(str); //expected result "Checking" TextBox
//result being obtained "Checking"
}
Since you are particular about "return true" in the TryAppend function, we can achieve by this workaround.

Categories