I have a JavaScript function which returns a function. What does it mean ?
function CheckShadowBounds(rounded) {
return function() {
};
}
How can I convert it to jQuery ?
It means it returns a function. Functions are first class objects and can be passed around just like strings, arrays, etc, etc.
The purpose of this example is to define rounded for the function. The same instance of rounded will be used every time the returned function is called.
You can't convert it to jQuery. jQuery is a set of predefined JavaScript functions that do things lots of people want to do, but which are relatively complex (often because of browser incompatibilities). This is not something that is relatively complex, so jQuery doesn't provide a helper function.
See Joel Spoelsky's intro to functional programming in JS to understand some ways a function returning a function can be useful: http://www.joelonsoftware.com/items/2006/08/01.html
This shouldn't need any changes to work in JQuery.
Related
I wonder if it's possible to give a a type/class to JavaScript functions.
Of course, the Object class/type of function is 'Function/function'.
http://bonsaiden.github.io/JavaScript-Garden/#types.typeof
However, in my project, somehow I want to define class for function to group them.
It's similar concept HTML/CSS DOM element class.
I have a function which args is a function, and I want to distinguish which type or class of function is passed to the function.
It does not work with any object method, just a function, but it can be distinguished like obj.hasOwnProperty('someClass') .
I just wonder if there's smart way, if you think impossible, please insist so.
Thanks.
PS. I do not why someone vote -1 and to close this question.
This is the matter of reflection of Javascript. It's ok if find some reflection factor of JS is limited. and I think it's not wise to avoid to make it clear that something is impossible in a certain language.
A function is an object. You can add your own custom properties to any function. So, if you want to set your own type on several different functions so you can test for that, you can just add the same custom property (with different values assigned to it) to each of those functions.
function myFunc1() {}
myFunc1.myType = "whatever1";
function myFunc2() {}
myFunc2.myType = "whatever2";
function myFunc3() {}
myFunc3.myType = "whatever3";
function callMe(cb) {
if (cb.myType === "whatever1") {
// code here
} else if (...) {
// code here
}
}
callMe(myFunc1);
Note, this is a bit unusual and if you explained the actual problem you were trying to solve, there is probably a more common design pattern that might help you.
#jfriend00 has suggested the answer.
FYI, functions are objects so they can have your own custom properties so you could make your own custom property.
He's right, so to add a class/property to any functions, simply do
var myFunction = function(foo){...};
myFunction['someClass'] = true;
//To distinguish
if (someFunction.hasOwnProperty('someClass'))
{
console.log('someFunction is someClass');
}
Excuse me first. because i don't know this is question is valid or not. i if any one clear my doubt then i am happy.
Basically : what is the different between calling a method like:
object.methodname();
$('#element').methodname();
calling both way is working, but what is the different between, in which criteria make first and second type of methods. is it available in the core javascript as well?
In case if i have a function is it possible to make 2 type of method call always?
Can any one give some good reference to understand correctly?
Thanks in advance.
The first syntax:
object.methodName();
Says to call a function, methodName(), that is defined as a property of object.
The second syntax:
$('#element').methodname();
Says to call a function called $() which (in order for this to work) must return an object and then call methodname() on that returned object.
You said that "calling both way is working," - so presumably you've got some code something like this:
var myObject = $('#element');
myObject.methodname();
This concept of storing the result of the $() function in a variable is commonly called "caching" the jQuery object, and is more efficient if you plan to call a lot of methods on that object because every time you call the jQuery $() function it creates another jQuery object.
"Is it available in the core javascript as well?" Yes, if you implement functions that return objects. That is, JS supports this (it would have to, since jQuery is just a JS library) but it doesn't happen automatically, you have to write appropriate function code. For example:
function getObject() {
return {
myMethod1 : function() { alert("myMethod1"); return this; },
myMethod2 : function() { alert("myMethod2"); return this; }
};
}
getObject().myMethod1().myMethod2();
In my opinion explaining this concept in more depth is beyond the scope of a Stack Overflow answer - you need to read some JavaScript tutorials. MDN's Working With Objects article is a good place to start once you have learned the JS fundamentals (it could be argued that working with objects is a JS fundamental, but obviously I mean even more fundamental stuff than that).
The difference is very subtle.
object.methodname();
This is when JavaScript has the object at hand.
$('#element').methodname();
If you are using jQuery, you are asking jQuery to select the object that has the id of #element. After that you invoke the method on the selected object.
Done a bit of Googling, but not quite finding what I want.
In an effort to reduce the amount of JAvascript lines my applications requires, I am trying to use as many reusable functions as possible.
The problem of course is trying to make these functions and flexible as possible.
So I have a form which is dynamically expanded by a cloning function using jQuery. In order for this to work, there are a few additional functions which need to run, for example, to correctly initialise datepickers, on the dynamically created elements.
These requirements are different depending upon which form is being cloned.
So, I call my cloning function as follows:
$('.button').click(function (){
var thisID = $(this).attr('id').replace('add', '');
cloneDetails(thisID, initialiseDates);
});
The cloneDetails function looks like this:
function cloneDetails(cur_num, callBackFunctions) {
/// do loads of stuff ///
callBackFunctions();
});
In this instance, the cloning function will run and do what it needs, then it'll run a second function call initialiseDates
What I want to be able to do though is specify several function names to run after the cloning function, with a call such as
cloneDetails(thisID, 'initialiseDates, doSomethingElse, doAnotherThing');
So, stating a list of functions to run after the cloneDetails function has been run.
I don't think I am setting up the callBack method correctly, and don't know how I should be.
Help much appreciated.
EDIT: I don't want to bundle all these functions into a single function, the whole point is these functions should all be useable independently and/or together.
I can think of several approaches:
You can split the string and use eval(name+'()') in each name in the list. Note that eval() can be evil, security wise.
Instead of a string, why not pass the functions as an array? Simply iterate over arguments[1..n] (arguments is an automatic variable which contains all function arguments).
Use an anonymous function:
cloneDetails(thisID, function(){
initialiseDates();
doSomethingElse();
doAnotherThing();
});
I like the last approach because:
It's the most flexible
Readable
Only adds a few bytes of code where you need them
Most performant
Another option (if you're using jQuery > 1.7): You can use the jQuery.Callbacks function.
cloneDetails(thisID, $.Callbacks()
.add(initialiseDates, doSomethingElse, doAnotherThing));
function cloneDetails(cur_num, callBackFunctions) {
/// do loads of stuff ///
callBackFunctions.fire();
});
am getting rid of all innerHTML and moving to strictly generated dom. reason below. have written a simple dom generator written in javascript that saves me a lot of work and keystrokes.
the big problem I'm having is how to implement an iterator. I feel like it should spit out a series of objects, sort of like a pipe, that the enclosing environment would process, but not much joy integrating the function. here is an example of my current solution
var div = E.div( '.myClass', 's.whiteSpace:nowrap',
'iterator': {
'set': { 'egg':'Scrambled Eggs', 'beer':'Chang Beer', 'yams':'Sweet Potatoes' },
'function':function(v,l) { return E.radio({'name':'myRadio', 'value':v},l); } } }
);
generates a div with three radio buttons. the iterator functionality inside E.div pulls out each value/label pair from the "set" and passes them to the "function", then processes the results of the function - in this case the function makes a radio button.
documentation on the factory plus better examples
http://code.google.com/p/chess-spider/wiki/DomFactory?ts=1302156868&updated=DomFactory
the current version of the javascript is
http://code.google.com/p/chess-spider/source/browse/http/scripts/factory.js
the reason why getting rid of innerHTML (and much raw html): would like the object responsible for the html to generate it as well as handle the triggers for it using closure functions. very big win, and impossible to do with quoted html. this gives the entire functionality contained in a nice "object".
This is more of a pointer. It seems the you can accomplish your task more easily using a JavaScript template engine. Try Handlebars.js and here's a good overview of Handlebars.js Iteration and many other features are available
Could someone write down a very simple basic example in javascript to conceptualize (and hopefully make me understand) how the jQuery plugin design pattern is done and how it works?
I'm not interested in how creating plugin for jQuery (so no jQuery code here at all).
I'm interested in a simple explanation (maybe with a bit of Javascript code) to explain how it is done the plugin concept.
Plz do not reply me to go and read jQuery code, I tried, but I it's too complex, otherwise I would have not post a question here.
Thanks!
jQuery has a library of functions stored in an internal object named fn. These are the ones that you can call on every jQuery object.
When you do $("div.someClass") you get a jQuery object containing all <div> elements of that class. Now you can do $("div.someClass").each( someFunction ) to apply someFunction to each of them. This means, that each() is one of the functions stored in fn (a built-in one in this case).
If you extend (add to) the internal fn object, then you automatically make available your custom function to the same syntax. Lets assume you have a function that logs all elements to the console, called log(). You could append this function to $.fn, and then use it as $("div.someClass").log().
Every function appended to the fn object will be called in such a way that inside the function body, the this keyword will point to the jQuery object you've used.
Common practice is to return this at the end of the custom function, so that method chaining does not break: $("div.someClass").log().each( someFunction ).
There are several ways to append functions to the $.fn object, some safer than others. A pretty safe one is to do:
jQuery.fn.extend({
foo: function() {
this.each( function() { console.log(this.tagName); } );
return this;
}
})
Tomalak already posted almost everything You need to know.
There is one last thing that helps jQuery do the trick with the this keyword.
it's amethod called apply()
var somefunction=function(){
alert(this.text);
}
var anObject={text:"hello"};
somefunction.apply(anObject);
//alert "hello" will happen
It really helps in creating abstractions so that framework/plugin users would just use this as intuition tells them, whatever there is inside Your code
It works, as many other js frameworks, using javascript prototype orientation.
For instance you can declare a simple function
var alertHelloWorld = function() {
alert('hello world');
}
And then tie it to an existing object (including DOM nodes)
document.doMyAlert = alertHelloWorld;
If you do this
document.doMyAlert();
The alertHelloWorld function will be executed
You can read more about javascript object prototyping here