How Can I Override A Function In Javascript - javascript

I have the following scripts:
<script ... jquery-1.9.1.js"></script>
<script ... dataTables.js"></script>
<script ... columnFilter.js"></script>
The following code exists in columnFilter.js:
(function ($) {
$.fn.columnFilter = function (options) {
//some code...
function _fnCreateCheckbox(oTable, aData) {
//some code...
}
};
})(jQuery);
What I would like to do is override function _fnCreateCheckbox(oTable, aData) with my own code. Im fairly new to javascript, so would appreciate an example.
I have tried simply grabbing the code above and adding it to it's own <script> tags, but that didn't work. It completely stopped the columnFilter.js from working (which is as expected I guess). Not really sure what else to try.

function _fnCreateCheckbox(oTable, aData) {
Only exists in the scope in which it was created as (function ($) { creates a function scope. You must edit it there. You can't override it outside the function.
EDIT: On a related note
If you are crafty with JS and you are trying to get that function to do something else only sometimes, you could pass some extra variables into your columnFilter plugin/function call and handle them in that function to do something else. I have no idea what column filter is, but let's pretend to call it on an element like so:
el.columnFilter({optionA: true, optionB: false});
If you wanted to do something else based on some data you have you could do,
el.columnFilter({optionA: true, optionB: false, extraOption: true});
Then in your script, depending on what your entire script does:
$.fn.columnFilter = function (options) {
//some code...
if(options.extraOption){
function _fnCreateCheckbox(oTable, aData) {
//some default code...
}
} else {
function _fnCreateCheckbox(oTable, aData) {
//my other code...
}
}
};
This is a crude example, but just to display your options.

I suppose you import the columnFilter.js file from some external source.
One option could be to copy the columnFilter.js file to your project's directory, modify it as you please and then import it from your project's directory.

You can override a function by reassigning its prototype. It is generally advised against though.
var d = new Date();
alert(d.getFullYear()); // 2013
Date.prototype.getFullYear = function() { return "Full Year"; }
alert(d.getFullYear()); // "Full Year"
http://jsfiddle.net/js5YS/

Related

how to create javascript library for self-written functions

** want to call common js for all validation for 20 jsp f**
function mAbcRefresher(refresh, refreshTime) {
//function code
}
function QWERTY(address){
//function code
}
function ASDF(address, value, refreshCallback){....
........
........
........`
I just copy these functions to a JS file and include the JS file in my html document. i need some standard way to write this type of validation code
Firstly created that common file eg. common.js. Add it to all your jsp pages. The standered way to write the code in js file
//common.js file
var common={
//function name
formvalidation : function(){
//eg.you want to get all required parts
var elements=$("input:visible, select:visible , textarea:visible");
$.each($(elements) function( index, element ){
//you can get do your code.
$(element).attr("attr");
});
}
//check condition and return false or true
}
above coders for write common functions.
now in jsp to call the function
Add this js file to head
then you can call the function in jsp
like:
$( document ).ready(function() {
//will return true or false
if(common.formvalidation()){
//submit or not
}
});
you can call another function inside this formvalidation() function
just you have assign a variable for this function
var common={
//function name
formvalidation : function(){
var date=this;
var result=date.formDate();
}
formDate : function(){
// do your code
}
}
You can look above code for the idea. definitely it will be helpful for you

Class is undefined in IE8

I have stupidly decided to support IE8 in my latest project, something which will no doubt go down in history as the dumbest idea of my life.
So the most fundamental problem I'm running into is that my main class variable is undefined. What I mean is I have a prototype set up in a file general.js that looks a bit like this:
var generalClass;
// jQuery Object
var $ = jQuery;
$(document).ready(function() {
// A general class for a general file.
generalClass = function() {
}
generalClass.prototype = {
}
new generalClass();
});
So the generalClass variable is filled up with my prototype/etc. I then include this in the head of my document and later on I call upon a function in that generalClass for something else, a bit like this:
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: ...,
data: {
},
success : function(data) {
// CALL MY FUNCTION:
generalClass.prototype.myFunction();
}
}
});
</script>
In every browser, from IE9 to Chrome this works. In IE8 this does not work, and generalClass is undefined. Why is it doing this to me?
I am not sure where you learned that pattern, but it should be more like this:
var generalClass;
// jQuery Object
//var $ = jQuery; <-- makes no sense $ should be jQuery already
$(document).ready(function() {
function GeneralClass() {}
GeneralClass.prototype = {
myFunction: function () {
alert("x");
}
};
generalClass = new GeneralClass();
});
and when you call it
generalClass.myFunction();

How to call function from another file with requireJS

I have two files - main, and events. I'm trying to call some function from one file to another.
So, this is how it looks:
events
require(['app/main'], function(call) {
// click event respond test
document.body.addEventListener("click", function(e) {
var target = e.target;
if (target.hasClass === "call"){
functionCall()();
}
});
});
main
define(["jquery"], function() {
// Call
var box = $('.box');
return function functionCall(){
box.addClass('visible');
}
});
What is wrong, can anyboyd help?
main:
define(["jquery"], function($) {
var main = {
functionCall: function(){
$('.box').addClass('visible');
}
}
return main;
});
events:
require(['jquery','app/main'], function($, main) {
$('body').on('click', function () {
if($(this).hasClass('call')){
main.functionCall();
}
});
});
One way is to add this code where you need to make call to function:
require('pathToModuleOrModuleName').functionYouWantToCall()
But if you have module defined or required in the beggining (as 'main' in the events), then in place where call to function needed just add:
call.functionName();
Unless my eyes deceive me the simplest change to make to your code would be to replace this:
functionCall()();
with this:
call();
since the function that the main module returns is imported as call in your events module, because that's how you name it in the callback passed to define.
Firstly your code has some basic problems
In the following code
define(["jquery"], function() {
Where are you referring the query inside the function definition.
I think you should first map the jquery defined into the function declaration like below
define(["jquery"], function($) {
Secondly, what is the () doing after the calling function?
if (target.hasClass === "call"){
functionCall()();
}
Remove the trailing () from that call. It should just be functionCall();

JQuery can't find variable from separate javascript file

I am using the cakephp framework and I created 2 separate javascript files and placed them into my webroot/js folder. The first javascript file contains modal dialog variables that contain the settings for the dialog boxes. The second javascript file contains other click event handlers that post data to an action and then open up the dialog.
The problem I am having is that the second file calls a variable from the first file using
$variablename and I get an error saying varaibleName is not defined.
Some code is below to show you what I mean.
From the first file:
var $editSel = $("#editSel_dialog").dialog(
{
autoOpen: false,
height: 530,
width: 800,
resizable: true,
modal: true,
buttons:
{
"Cancel": function()
{
$(this).dialog("close");
}
}
});
From the second file:
$('.neweditSel_dialog').live('click', function()
{
$.ajaxSetup({ async: false });
var selected = [];
$("#[id*=LocalClocks]").each(function()
{
if(false != $(this).is(':checked'))
{
var string = $(this).attr('id').replace('LocalClocks', '');
string = string.substring(10);
selected.push(string);
}
});
if(0 === selected.length)
{
$selError.dialog('open');
$selError.text('No Local Clocks Were Selected')
}
else
{
$.post('/LocalClocks/editSelected', { "data[Session][selected]": selected }, function(data)
{
});
$editSel.load($(this).attr('href'), function ()
{
$editSel.dialog('open');
});
}
return false;
});
This was working when I was using jquery-1.4.2.min.js, but I am using jquery1.7 now.
I also ended up putting the first file with all the variables inside of $(document).ready(function(){}); I tried putting the second file inside of a document.ready() function but that made no difference.
Any help would be great.
Thanks
You are dealing with an issue in scope. In javascript:
function foo() {
var greet = "hi";
}
function bar() {
console.log(greet); // will throw error
}
However:
var greet;
function foo() {
greet = "hi";
}
function bar() {
console.log(greet); // will log "hi"
}
You must define your variable in a common parent of both functions that need to access it. Unfortunately, since you do not use any modeling convention or framework, that is the window object (why are global variables bad?).
So, you must define var $whateveryouneed before and outside of both $(document).readys.
Also, keep the declaration and definition seperate. Your definition instantiates a jQuery object, so you must encapsulate it inside a $(document).ready() (use $(function() {}) instead):
var $editSel;
$(function () {
$editSel = $("#editSel_dialog").dialog(
{
autoOpen: false,
height: 530,
width: 800,
resizable: true,
modal: true,
buttons:
{
"Cancel": function()
{
$(this).dialog("close");
}
}
});
});
I don't think you can guarantee the order in which handlers will be fired, which means that the document ready may be fired in different order than you expect. Is the variable you are trying to access in the second file a global variable? Try to think about your variables scope as I would have thought this is the issue.
You cannot guarantee that one file will be loaded before the other. And you cannot guarantee that document.ready in one file will fire before the other.
Therefore, I suggest you wrap your code in functions and call them in a single document.ready handler in the order you need.
For example:
function initVariables(){
window.$editSel = ... // your code from the first file here
}
function initHandlers(){
// your code from the second file here
}
And then:
$(document).ready(function() {
initVariables();
initHandlers();
});
You'll notice that I used the global window object to expose your variable. It would be even better if you used a common namespace for them.

Organzing javascript / jQuery for multiple web pages

To keep organized, I'd like to keep all the javascript for my site in a single file:
scripts.js
However, some of my scripts are only used on on some pages, other scripts are only used on other pages.
In my document-ready function it looks like this:
function home_page() {
// image rotator with "global" variables I only need on the home page
}
$('#form')... // jQuery form validation on another page
The problem with this, is that I am getting javascript to execute on pages it's not even needed. I know there is a better way to organize this but I'm not sure where to start...
One thing you could do would be to use classes on the <html> or <body> tag to establish the type of each page. The JavaScript code could then use fairly cheap .is() tests before deciding to apply groups of behaviors.
if ($('body').is('.catalog-page')) {
// ... apply behaviors needed only by "catalog" pages ...
}
Even in IE6 and 7, making even a few dozen tests like that won't cause performance problems.
I usually do something like this, or some variation (a little pseudo code below) :
var site = {
home: {
init: function() {
var self=this; //for some reference later, used quite often
$('somebutton').on('click', do_some_other_function);
var externalFile=self.myAjax('http://google.com');
},
myAjax: function(url) {
return $.getJSON(url);
}
},
about: {
init: function() {
var self=this;
$('aboutElement').fadeIn(300, function() {
self.popup('This is all about me!');
});
},
popup: function(msg) {
alert(msg);
}
}
};
$(function() {
switch($('body').attr('class')) {
case 'home':
site.home.init();
break;
case 'about':
site.about.init();
break;
default:
site.error.init(); //or just home etc. depends on the site
}
});
I ususally have an init() function that goes something like this:
function init() {
if($('#someElement').length>1) {
runSomeInitFunction()
}
... more of the same for other elements ...
}
Basically just check to see if the element exists on the page, if it does, run its own initialization function, if not, skip it.
The whole JS codes is cached by the browser after the first page load anyway, so there's no point in fragmenting your JS file down into page-specific pieces. That just makes it a maintenance nightmare.
You could use for each page object literals to get different scopes.
​var home = {
other: function() {
},
init: function() {
}
};
var about = {
sendButton: function(e) {
},
other: function() {
},
init: function() {
}
}
var pagesToLoad = [home, about];
pagesToLoad.foreach(function(page) {
page.init();
});​

Categories