JQuery can't find variable from separate javascript file - javascript

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.

Related

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();

How Can I Override A Function In 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/

jQuery: Call a function twice

I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});

How do I set doubleClick function to call custom function in jqGrid

I have added a custom edit button control on the jqGrid navigator as follows:
jQuery("#grid").navButtonAdd('#pager',
{
caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editSelectedRow,
position: "last",
title:"click to edit selected row",
cursor: "pointer",
id: "edit-row"
}
);
So that rather than use the default function: editGridRow, it uses my custom function editSelectedRow. However, I also want to add the doubleClick function to so that it calls editSelectedRow on doubleClick.
using the default editGridRow function works as such
ondblClickRow: function()
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
jQuery(this).jqGrid('editGridRow', rowid);
}
However, when I replace the default editGridRow function with my default function editSelectedRow as such,
ondblClickRow: function()
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
jQuery(this).jqGrid('editSelectedRow', rowid);
}
I get the following error within firebug:
uncaught exception: jqGrid - No such method: editSelectedRow
The function editSelectedRow however does exist and works with clicking the custom edit button. Please help, thanks.
UPDATE:
#Oleg: As requested here's the code defining method: editSelectedRow
function editSelectedRow(rowid)
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
if( rowid != null )
{
var dialogId = '#edit-form-dialog';
var dialogTitle = 'Edit Customer';
$(dialogId).load('/customer/edit/id/' + rowid, function ()
{
$(this).dialog(
{
modal: false,
resizable: true,
minWidth: 650,
minHeight: 300,
height: $(window).height() * 0.95,
title: dialogTitle,
buttons:
{
"Save": function ()
{
var form = $('form', this);
$(form).submit();
$("#grid").trigger("reloadGrid");
},
"Cancel": function ()
{
$("#grid").trigger("reloadGrid");
$(this).dialog('close');
}
}
});
LaunchEditForm(this);
});
}
else
{
jQuery( "#dialogSelectRow" ).dialog();
}
return false;
}
#Oleg: Thanks, you advised against using a custom method editSelectedRow in place of method editGridRow. The reason I am using this is that my forms are Zend Forms and I need all the bells and whistles of Zend Form to be available. The server generates this form and it's loaded into a dialog form. If there's a way to still achieve this without resorting to my editSelectedRow custom method, I'd be glad to learn it. Thanks.
You question is pure JavaScript question.
If you define the function editSelectedRow as
function editSelectedRow(rowid)
{
...
}
you can call it as editSelectedRow(rowid) and not as jQuery(this).jqGrid('editSelectedRow', rowid);.
Another problem is that you use this inside of he body of editSelectedRow function. It's not correct. You can define editSelectedRow function in a little another way
var editSelectedRow = function (rowid) {
...
};
In the case editSelectedRow will be able to bind this to any value. To do this you need use another form of invocation of the function. Inside of ondblClickRow it will be
ondblClickRow: function () {
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
editSelectedRow.call(this, rowid);
}
In the above example the first parameter of call is the value used as this inside of the function. We forward just the current this value forward to editSelectedRow. If we would use the form editSelectedRow(rowid); for the invocation of the function the value of this inside of function will be initialized to window object.
The usage of editSelectedRow inside of navButtonAdd can stay unchanged.

How to place a jQuery snippet into a global file

I have a JavaScript file here http://www.problemio.com/js/problemio.js and I am trying to place some jQuery code into it that looks like this:
$(document).ready(function()
{
queue = new Object;
queue.login = false;
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function ()
{
$("#login_div").hide();
$("#newprofileform").show();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
queue.voteUp = $(this).attr('problem_id');
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id );
queue.voteUp = problem_id;
var dataString = 'problem_id=' + problem_id + '&vote=+';
if ( queue.login = false)
{
// Call the ajax to try to log in...or the dialog box to log in. requireLogin()
}
else
{
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// Try to update the vote count on the page
//$('p').each(function()
//{
//on each paragraph in the page:
// $(this).find('span').each()
// {
//find each span within the paragraph being iterated over
// }
//}
},
error : function(data)
{
alert ("vote error");
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
alert ("after dialog was open");
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
} // End of error case
}
}); // Closing AJAX call.
};
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function()
{
alert("in login button fnction");
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
There are two reasons why I am trying to do that:
1) I am guessing this is just good practice (hopefully it will be easier to keep track of my global variables, etc.
2) More importantly, I am trying to call the voteUp(someId) function in the original code from the problemio.js file, and I am getting an error that it is an undefined function, so I figured I'd have better luck calling that function if it was in a global scope. Am I correct in my approach?
So can I just copy/paste the code I placed into this question into the problemio.js file, or do I have to remove certain parts of it like the opening/closing tags? What about the document.ready() function? Should I just have one of those in the global file? Or should I have multiple of them and that won't hurt?
Thanks!!
1) I am guessing this is just good practice (hopefully it will be
easier to keep track of my global variables, etc.
Yes and no, you now have your 'global' variables in one spot but the chances that you're going to collide with 'Global' variables (ie those defined by the browser) have increased 100% :)
For example say you decided to have a variable called location, as soon as you give that variable a value the browser decides to fly off to another URL because location is a reserved word for redirecting.
The solution to this is to use namespacing, as described here
2) More importantly, I am trying to call the voteUp(someId) function
in the original code from the problemio.js file, and I am getting an
error that it is an undefined function, so I figured I'd have better
luck calling that function if it was in a global scope. Am I correct
in my approach?
Here's an example using namespacing that will call the voteUp function:
(function($) {
var myApp = {};
$('.vote_up').click(function(e) {
e.preventDefault();
myApp.voteUp();
});
myApp.voteUp = function() {
console.log("vote!");
}
})(jQuery);
What about the document.ready() function? Should I just have one of
those in the global file? Or should I have multiple of them and that
won't hurt?
You can have as many document.ready listeners as you need, you are not overriding document.ready you are listening for that event to fire and then defining what will happen. You could even have them in separate javascript files.
Be sure your page is finding the jquery file BEFORE this file is included in the page. If jquery is not there first you will get function not defined. Otherwise, you might have other things conflicting with your jquery, I would look into jquery noConflict.
var j = jQuery.noConflict();
as seen here:
http://api.jquery.com/jQuery.noConflict/
Happy haxin
_wryteowl
Extending what KreeK has already provided: there's no need to define your "myApp" within the document ready function. Without testing, I don't know off the top of my head if doing so is a potential source for scope issues. However, I CAN say that the pattern below will not have scope problems. If this doesn't work, the undefined is possibly a script-loading issue (loading in the right order, for example) rather than scope.
var myApp = myApp || {}; // just adds extra insurance, making sure "myApp" isn't taken
myApp.voteUp = function() {
console.log("vote!");
}
$(function() { // or whatever syntax you prefer for document ready
$('.vote_up').click(function(e) {
e.preventDefault();
myApp.voteUp();
});
});

Categories