NOTE:: I have replaced some code with comments to make it much shorter and more readable
I am working with Javascript (Ajax) and PHP (Laravel). I have run into a predicament! When calling an ajax function I have two listener to show a loading symbol while the ajax is processing, and then hide it again once it's done.
$( document ).ajaxStart( function() {
$( '#loading' ).css( 'display', 'block' );
} );
$( document ).ajaxStop( function() {
$( '#loading' ).css( 'display', '' );
} );
When you click on the submit button, the HTML onclick says to go to this function which is working just fine:
function submit( button ) {
var table = $( button ).closest( '.popup' ).find( 'table:first' );
var verified = verifyTable( table );
if ( verified == -1 ) {
return -1;
}
if ( table.hasClass( 'campaigns' ) ) {
campaign = table.find( '.campaign:first' );
submitNewCampaign( campaign );
} else if ( table.hasClass( 'groups' ) ) {
groups = table.find( 'tr.group' );
for ( var i = 0; i < groups.length; ++i ) {
submitNewGroup( groups.eq( i ) );
}
} else if ( table.hasClass( 'keywords' ) ) {
keywords = table.find( 'tr.keyword' );
for ( var i = 0; i < keywords.length; ++i ) {
submitNewKeyword( keywords.eq( i ) );
}
}
closePopup();
}
If from there you are sent to submitNewCampaign(), everything works just fine.
function submitNewCampaign( campaign ) {
// Set campaign variables
$.ajax({
url : '/ajax/addCampaign',
type : 'POST',
data : { // set campaign data },
success : function( result ) {
// get all groups in campaigns and loop through
for ( var i = 0; i < groups.length; ++i ) {
// set group variables
$.ajax({
url : '/ajax/addGroup',
type : 'POST',
async : false,
data : { // set group data },
success : function( result ) {
// get all keywords in group and loop
for ( var i = 0; i < keywords.length; i++ ) {
// set keyword variables
$.ajax({
url : '/ajax/addKeyword',
type : 'POST',
async : false,
data : { // set keyword data },
success : function( result ) { // done },
error : function( result ) {
alert( "error adding new keyword (name - " + keyword_name + ")");
console.log( result );
}
);
}
},
error : function( result ) {
alert( "error adding new group (name - " + group_name + ")" );
console.log( result );
}
});
}
},
error : function( result ) {
alert( "error adding new campaign (name - " + campaign_name + "): " + JSON.parse( xhr.responseText ) );
}
});
}
However if you are send to either submitNewGroup() or submitNewKeyword(), the loading image does not appear.
function submitNewGroup ( group ) {
// set group variables
$.ajax({
url : '/ajax/addGroup',
type : 'POST',
async : false,
data : { // set group data },
success : function( result ) {
// get all keywords in group and loop
for ( var i = 0; i < keywords.length; ++i ) {
// set all keyword variables
$.ajax({
url : '/ajax/addKeyword',
type : 'POST',
async : false,
data : { // set all keyword data },
success : function( result ) { // done },
error : function( result ) {
console.log( result );
}
});
}
},
error : function( result ) {
console.log( result );
}
});
}
function submitNewKeyword( keyword ) {
// set keyword variables
$.ajax({
url : '/ajax/addKeyword',
type : 'POST',
async : false,
data : { // set keyword data },
success : function( result ) { //done },
error : function( result ) {
console.log( result );
}
});
}
IMPORTANT: No errors appear in the log when any of the three functions are called. All three complete their assigned tasks with no issues.
I tried a few things and the one that made it work was: I removed async from the outer most ajax call for both group and keyword
Related
Im getting Uncaught TypeError: Cannot use 'in' operator to search for 'length' in on a autocomplete field. This is the code:
enable_autocomplete: function() {
$( 'input.fm-autocomplete:visible' ).each( function() {
if ( !$( this ).hasClass( 'fm-autocomplete-enabled' ) ) {
var ac_params = {};
var $el = $( this );
var $hidden = $el.siblings( 'input[type=hidden]' ).first();
ac_params.select = function( e, ui ) {
e.preventDefault();
$el.val( ui.item.label );
$hidden.val( ui.item.value ).trigger( 'change' );
};
ac_params.focus = function( e, ui ) {
e.preventDefault();
$el.val( ui.item.label );
}
if ( $el.data( 'action' ) ) {
ac_params.source = function( request, response ) {
// Check for custom args
var custom_args_js_event = $el.data( 'customArgsJsEvent' );
var custom_data = '';
if ( 'undefined' !== typeof custom_args_js_event && null !== custom_args_js_event ) {
var custom_result = $el.triggerHandler( custom_args_js_event );
if ( 'undefined' !== typeof custom_result && null !== custom_result ) {
custom_data = custom_result;
}
}
$.post( ajaxurl, {
action: $el.data( 'action' ),
fm_context: $el.data( 'context' ),
fm_subcontext: $el.data( 'subcontext' ),
fm_autocomplete_search: request.term,
fm_search_nonce: fm_search.nonce,
fm_custom_args: custom_data
}, function( result ) {
console.log( result );
$.parseJSON( response( result ) );
} );
};
All other questions related to this error suggested a $.parseJSON but it's not working for me. This is the console.log of result when i type eco:
[{"label":"Economy Talks","value":1480},{"label":"Economy","value":212},{"label":"Economy motors","value":2038},{"label":"Telecomunica\u00e7\u00f5es","value":402}]
Console.log of response:
function (){return a.apply(b||this,c.concat(e.call(arguments)))}
It finds the right suggestions but then i get Uncaught TypeError: Cannot use 'in' operator to search for 'length' in and i'm not able to select any option. Any ideas how to fix this?
I uploaded the dropdown to my web site, somehow it looks double:)
Like this:
But, that's not the only problem,
Another problem is that Elements do not appear in the <select> list, but when I add some sample <option>Sample</option> all elements appear.
My Select Codes:
<select class="selectpicker" id="List" multiple data-live-search="true" data-actions-box="true" data-selected-text-format="count>1">
<option>asdd</option>
<option>3</option>
<option>ssasd</option>
<option>adsd</option>
<option>a</option>
<option>sasd</option>
<option>adsd</option>
</select>
My JavaScript code:
$.ajax({
type : "POST",
url : "db/../..",
dataType : "json"
})
.done(function( result ) {
if ( typeof result.error !== "undefined" ) {
// Error
dialog.close();
alertDialog( "Hata", result.error, BootstrapDialog.TYPE_DANGER );
} else if ( typeof result.List !== "undefined" && $.isArray( result.List ) ) {
// A proper result
if ( result.FirmList.length < 1 ) {
// No records found
dialog.close();
alertDialog( "Error", "Nothing Found!", BootstrapDialog.TYPE_WARNING );
} else {
// Parse details
var f = result.List;
for ( var i = 0; i < f.length; i++ ) {
var op = document.createElement( "option" );
op.value = f[ i ].Id;
op.textContent = f[ i ].Name;
document.getElementById( "List" ).appendChild( op );
}
$( "#select" ).chosen();
}
} else {
dialog.close();
alertDialog( "Error", "No Idea!", BootstrapDialog.TYPE_DANGER );
}
})
.fail(function(a, b, c) {
dialog.close();
alertDialog( "Error",
"Error",
BootstrapDialog.TYPE_DANGER );
});
I am working on JavaScript accordion and somehow i struck on targeting accordion ID instead of its <li>
Basically, I want below to generate two accordion if there are two markups like this
<div id="st-accordion" class="st-accordion">
<ul>
<li>
{tag_name_nolink}
<div class="st-content">
{tag_Partners Module tag}
</div>
</li>
</ul>
</div>
If there are two <div id="st-accordion" class="st-accordion">.......</div> then it should display two working accordions but it is making two working accordions when there are two <li> in the div.
Here is the JS and Fiddles
WORKING | NOT WORKING
(function( window, $, undefined ) {
var $event = $.event, resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
$.Accordion = function( options, element ) {
this.$el = $( element );
// list items
this.$items = this.$el.children('ul').children('li');
// total number of items
this.itemsCount = this.$items.length;
// initialize accordion
this._init( options );
};
$.Accordion.defaults = {
// index of opened item. -1 means all are closed by default.
open : -1,
// if set to true, only one item can be opened. Once one item is opened, any other that is opened will be closed first
oneOpenedItem : false,
// speed of the open / close item animation
speed : 600,
// easing of the open / close item animation
easing : 'easeInOutExpo',
// speed of the scroll to action animation
scrollSpeed : 900,
// easing of the scroll to action animation
scrollEasing : 'easeInOutExpo'
};
$.Accordion.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Accordion.defaults, options );
// validate options
this._validate();
// current is the index of the opened item
this.current = this.options.open;
// hide the contents so we can fade it in afterwards
this.$items.find('div.st-content').hide();
// save original height and top of each item
this._saveDimValues();
// if we want a default opened item...
if( this.current != -1 )
this._toggleItem( this.$items.eq( this.current ) );
// initialize the events
this._initEvents();
},
_saveDimValues : function() {
this.$items.each( function() {
var $item = $(this);
$item.data({
originalHeight : $item.find('a:first').height(),
offsetTop : $item.offset().top
});
});
},
// validate options
_validate : function() {
// open must be between -1 and total number of items, otherwise we set it to -1
if( this.options.open < -1 || this.options.open > this.itemsCount - 1 )
this.options.open = -1;
},
_initEvents : function() {
var instance = this;
// open / close item
this.$items.find('a:first').bind('click.accordion', function( event ) {
var $item = $(this).parent();
// close any opened item if oneOpenedItem is true
if( instance.options.oneOpenedItem && instance._isOpened() && instance.current!== $item.index() ) {
instance._toggleItem( instance.$items.eq( instance.current ) );
}
// open / close item
instance._toggleItem( $item );
return false;
});
$(window).bind('smartresize.accordion', function( event ) {
// reset orinal item values
instance._saveDimValues();
// reset the content's height of any item that is currently opened
instance.$el.find('li.st-open').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ) + $this.find('div.st-content').outerHeight( true ) );
});
// scroll to current
if( instance._isOpened() )
instance._scroll();
});
},
// checks if there is any opened item
_isOpened : function() {
return ( this.$el.find('li.st-open').length > 0 );
},
// open / close item
_toggleItem : function( $item ) {
var $content = $item.find('div.st-content');
( $item.hasClass( 'st-open' ) )
? ( this.current = -1, $content.stop(true, true).fadeOut( this.options.speed ), $item.removeClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' )
}, this.options.speed, this.options.easing ) )
: ( this.current = $item.index(), $content.stop(true, true).fadeIn( this.options.speed ), $item.addClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' ) + $content.outerHeight( true )
}, this.options.speed, this.options.easing ), this._scroll( this ) )
},
// scrolls to current item or last opened item if current is -1
_scroll : function( instance ) {
var instance = instance || this, current;
( instance.current !== -1 ) ? current = instance.current : current = instance.$el.find('li.st-open:last').index();
$('html, body').stop().animate({
scrollTop : ( instance.options.oneOpenedItem ) ? instance.$items.eq( current ).data( 'offsetTop' ) : instance.$items.eq( current ).offset().top
}, instance.options.scrollSpeed, instance.options.scrollEasing );
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.accordion = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
logError( "cannot call methods on accordion prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for accordion instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
$.data( this, 'accordion', new $.Accordion( options, this ) );
}
});
}
return this;
};
})( window, jQuery );
somebody help please?
You have 2 elements with the same ID, and ID must be unique, so all you have to do is using class instead of ID :
$(function() {
$('.st-accordion').accordion({
oneOpenedItem : true
});
});
here is the jsFiddle
Since changing to a new theme I have some probs including DataTables. jQuery is only called once and it is placed at the correct position, so basically everything correct.
I receive messages like
TypeError: $(...).DataTable is not a function
or
TypeError: $ is undefined
Beneath the DataTables I have a different JS with load() and with a similar problem. There I could fix it while putting this:
jQuery(document).ready(function($){
before this:
$("#tmp").load("tmp.htm")
I've read on some boards, that there could be an issue with the place-holder $. Anyway, the part above solves my problem. But back to the DataTables. I think it's the same problem, but I'm unable to understand the problem.
My Table starts with:
$(document).ready(function() {
var tabelle = $('#mytable').DataTable(
But with this before..
jQuery(document).ready(function($){
I do only get errors. Could somebody please help me?
++++++++ UPDATE ++++++++
<script type="text/javascript" language="javascript" class="init">
$.fn.dataTable.pipeline = function ( opts ) {
// Configuration options
var conf = $.extend( {
pages: 5, // number of pages to cache
url: '', // script url
data: null, // function or object with parameters to send to the server
// matching how `ajax.data` works in DataTables
method: 'GET' // Ajax HTTP method
}, opts );
// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;
return function ( request, drawCallback, settings ) {
var ajax = false;
var requestStart = request.start;
var requestLength = request.length;
var requestEnd = requestStart + requestLength;
if ( settings.clearCache ) {
// API requested that the cache be cleared
ajax = true;
settings.clearCache = false;
}
else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
// outside cached data - need to make a request
ajax = true;
}
else if ( JSON.stringify( request.order ) !== JSON.stringify( cacheLastRequest.order ) ||
JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
JSON.stringify( request.search ) !== JSON.stringify( cacheLastRequest.search )
) {
// properties changed (ordering, columns, searching)
ajax = true;
}
// Store the request for checking next time around
cacheLastRequest = $.extend( true, {}, request );
if ( ajax ) {
// Need data from the server
if ( requestStart < cacheLower ) {
requestStart = requestStart - (requestLength*(conf.pages-1));
if ( requestStart < 0 ) {
requestStart = 0;
}
}
cacheLower = requestStart;
cacheUpper = requestStart + (requestLength * conf.pages);
request.start = requestStart;
request.length = requestLength*conf.pages;
// Provide the same `data` options as DataTables.
if ( $.isFunction ( conf.data ) ) {
// As a function it is executed with the data object as an arg
// for manipulation. If an object is returned, it is used as the
// data object to submit
var d = conf.data( request );
if ( d ) {
$.extend( request, d );
}
}
else if ( $.isPlainObject( conf.data ) ) {
// As an object, the data given extends the default
$.extend( request, conf.data );
}
settings.jqXHR = $.ajax( {
"type": conf.method,
"url": conf.url,
"data": request,
"dataType": "json",
"cache": false,
"success": function ( json ) {
cacheLastJson = $.extend(true, {}, json);
if ( cacheLower != requestStart ) {
json.data.splice( 0, requestStart-cacheLower );
}
json.data.splice( requestLength, json.data.length );
drawCallback( json );
}
} );
}
else {
json = $.extend( true, {}, cacheLastJson );
json.draw = request.draw; // Update the echo for each response
json.data.splice( 0, requestStart-cacheLower );
json.data.splice( requestLength, json.data.length );
drawCallback(json);
}
}
};
$.fn.dataTable.Api.register( 'clearPipeline()', function () {
return this.iterator( 'table', function ( settings ) {
settings.clearCache = true;
} );
} );
$(document).ready(function() {
var tabelle = $('#mytable').DataTable(
{
"processing": true,
"serverSide": true,
"ajax": $.fn.dataTable.pipeline(
{
url: 'source.htm',
pages: 1
}
),
.....
}
);
} );
</script>
I had same problem and the code below solves the issue
jQuery(document).ready(function($){
This solves the problem. Adding the line below the initiating body-tag:
<script> $ = jQuery; </script>
Good day, first I would like to tell that I am not proud to post a whole source code. I couldn't isolate the problem in a smaller chunk.
Here is a snapshot of the file:
getRoomById : function( areaId, roomId ) {
if ( this.hAreas.get( areaId ) !== null && this.hAreas.get( areaId )[ roomId ] !== undefined )
{
//I can get here...
//alert( uneval( this.hAreas.get( areaId ) ) );
// returns: ({'000001':{areaId:"000001", roomId:"000001", Informations:{Name:"Room 1"}}, '000002':{areaId:"000001", roomId:"000002", Informations:{Name:"Room 2"}}, '000003':{areaId:"000001", roomId:"000003", Informations:{Name:"Room 3"}}})
//alert( roomId );
// returns: 000003
return this.hAreas.get( areaId )[ roomId ];
// returns: undefined
}
},
and the whole file is there: http://jsfiddle.net/JSWCu/2/
The problem: I have a method which tests the arguments against a JS.Hash containing an object. That if hopefully returns true but once inside, I can't get (either alert or return) the object inside that JS.Hash (an undefined is returned).
Thank you! your help is greatly appreciated. I would also appreciate tips to avoid such errors.
Edit: here is the whole codes. Sorry It's really big. It's just starting to get complex and I couldn't (for now) isolate the problems to a smaller piece of codes:
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript">
JSCLASS_PATH = 'http://www.poc.ca/cybrix/src';
function appendConsole( input ) {
document.getElementById( "console" ).innerHTML += input + "<br />";
}
</script>
<script type="text/javascript" src="http://www.poc.ca/cybrix/src/loader-browser.js"></script>
<script type="text/javascript">
JS.require('JS.Hash', 'JS.Observable', function() {
var AreaLists = {
"000001" : { "Name" : "Test Area", "Loaded" : false },
};
var World = new JS.Class({
hAreas : new JS.Hash([]),
getAreas : function( areaId ) {
if ( ! this.hAreas.get( areaId ) && AreaLists[ areaId ] !== undefined )
{
//TODO: Load from external sources
this.hAreas.put( areaId, {
"000001" : new Room( areaId, "000001", { "Name" : "Room 1" } ),
"000002" : new Room( areaId, "000002", { "Name" : "Room 2" } ),
"000003" : new Room( areaId, "000003", { "Name" : "Room 3" } ),
});
AreaLists[ areaId ].Loaded = true;
appendConsole( "Areas #" + areaId + " : " + AreaLists[ areaId ].Name + " Created" );
}
return this.hAreas.get( areaId );
},
getRoomById : function( areaId, roomId ) {
if ( this.hAreas.get( areaId ) !== null && this.hAreas.get( areaId )[ roomId ] !== undefined )
{
//I can get here...
//alert( uneval( this.hAreas.get( areaId ) ) );
// returns: ({'000001':{areaId:"000001", roomId:"000001", Informations:{Name:"Room 1"}}, '000002':{areaId:"000001", roomId:"000002", Informations:{Name:"Room 2"}}, '000003':{areaId:"000001", roomId:"000003", Informations:{Name:"Room 3"}}})
//alert( roomId );
// returns: 000003
return this.hAreas.get( areaId )[ roomId ];
// returns: undefined
}
},
reloadAreas : function( areaId ) {
//Triggered by Tick only if there is no players
},
addCharacter : function( areaId, roomId, character ) {
if ( this.hAreas.get( areaId ) && this.hAreas.get( areaId )[ roomId ] )
{
this.hAreas.get( areaId )[ roomId ].addCharacter( character );
}
},
removeCharacter : function( areaId, roomId, character ) {
return this.hAreas.get( areaId )[ roomId ].removeCharacter( character );
}
});
var Room = new JS.Class({
hDoors : new JS.Hash([]),
hExits : new JS.Hash([]),
hBodies : new JS.Hash([]),
hObjects : new JS.Hash([]),
initialize : function( areaId, roomId, Informations ) {
this.areaId = areaId;
this.roomId = roomId;
this.Informations = Informations;
//TODO: Load from external sources
if ( areaId == "000001" && roomId == "000003" )
{
this.hObjects.put("000001", new Objects("000001", { "Name" : "A table", "Type" : 0 }) );
this.hObjects.put("000002", new Objects("000002", { "Name" : "A water fountain", "Type" : 1 }) );
}
appendConsole( "Room: #" + this.areaId + "-" + this.roomId + " : " + this.Informations.Name + " Created" );
},
addCharacter : function( character ) {
this.hBodies.put( character.characterId , character );
character.onArriveRoom( this );
if ( ! character.Informations.Stealth )
{
//TODO: Broadcast Informations to others
appendConsole( character.Informations.Name + " has arrived to " + this.Informations.Name );
}
},
removeCharacter : function( character ) {
var characterId = ( typeof character == "object" ) ? character.characterId : character,
currentCharacter = this.hBodies.remove( characterId );
character.onLeaveRoom( this );
if ( currentCharacter !== null )
{
//TODO: Broadcast Informations to others
appendConsole( character.Informations.Name + " has left " + this.Informations.Name );
return currentCharacter;
}
return undefined;
},
onArrive : function() {
},
onLeave : function() {
},
getObjects : function( objectId, hash ) {
if ( this.hObjects.get( objectId ) )
{
var currentObjects = this.hObjects.get( objectId );
if ( hash )
{
return new JS.Hash([
currentObjects.objectId, currentObjects
]);
}
return currentObjects;
}
return this.hObjects;
},
toString : function( characterId ) {
}
});
var Objects = new JS.Class({
objectsTypes : {
0 : "lies",
1 : "stands"
},
initialize : function( objectId, Informations ) {
this.objectId = objectId;
this.Informations = Informations;
appendConsole( "Object: #" + this.objectId + " : " + this.Informations.Name + " Created" );
},
toString : function() {
return this.Informations.Name + " " + this.objectsTypes[ this.Informations.Type ] + " here.";
}
});
var Character = new JS.Class({
Pet : undefined,
initialize : function( characterId, Informations ) {
this.characterId = characterId;
this.Informations = Informations;
this.areaId = this.Informations.Zone.split("-")[ 0 ];
this.roomId = this.Informations.Zone.split("-")[ 1 ];
if ( this.Informations.Pet !== undefined )
{
//TODO: Load from external sources
if ( this.Informations.Pet === "000001" )
{
this.Pet = new Pet( "000001", { "Name" : "Molten Panther", "Zone" : this.areaId + "-" + this.roomId, "Stealth" : false } );
World.addCharacter( this.Pet.getArea() , this.Pet.getRoom() , this.Pet );
var petRoom = World.getRoomById( this.Pet.getArea() , this.Pet.getRoom() );
alert( petRoom ); // = undefined ????
}
}
appendConsole( "Character: #" + this.characterId + " : " + this.Informations.Name + " Created" );
},
onArriveRoom : function ( currentRoom ) {
},
onLeaveRoom : function( currentRoom ) {
},
onArrive : function() {
},
onLeave : function() {
},
getRoom : function() {
return this.roomId + "";
},
getArea : function() {
return this.areaId + "";
},
getInformations : function() {
return this.Informations;
},
hasPet : function() {
return ( typeof this.Pet == "object" );
},
getPet : function() {
return this.Pet;
},
equals : function( character ) {
return ( character instanceof this.klass ) && character.Informations.Name === this.Informations.Name;
}
});
var Pet = new JS.Class( Character, {
initialize : function( characterId, Informations ) {
this.callSuper();
appendConsole( "Pet: " + this.Informations.Name + " Created" );
}
});
//Tests
var World = new World();
var AreaOne = World.getAreas( "000001" );
var Cybrix = new Character( "000001", { "Name" : "Cybrix", "Zone" : "000001-000003", "Stealth" : false, "Pet" : "000001" } );
if ( World.getAreas( Cybrix.getArea() ) )
{
World.addCharacter( Cybrix.getArea() , Cybrix.getRoom() , Cybrix );
//Cybrix = World.removeCharacter( Cybrix.getArea() , Cybrix.getRoom() , Cybrix );
}
});
</script>
</head>
<body style="margin: 0; padding: 0;">
<div id="console" style="display: block; background-color: #000; height: 100%; color: #FFF; font-family: Lucida Console;"></div>
</body>
</html>
I've been playing around with your example on jsfiddle and I'm running into some rather odd behavior. In your Character class' initialization method you're calling the World.getRoomById() method in question and assigning it to a variable called petRoom.
As your code stands, when you alert(petRoom) you do get undefined. However, if you alert(petRoom.roomId) you get 000003 as intended so my guess is it's not really returning a true undefined. If you log petRoom to chrome's console it classifies it as a constructor and not an object. I'm not really sure what's going on there, but I thought it'd give some extra direction. I'll keep playing.....
UPDATE: The issue is that you're overriding the Room class' toString() method and not returning anything. By default, alerting something cast it to a string using the object's toString() method and because you've overridden that and aren't returning a value you get undefined.
var Room = new JS.class({
...
snip
....
toString: function(characterId) {
}
});
Answering your question in the comments
how could the if passes when once you return the value it is undefined
You're using the comparison this.hAreas.get( areaId )[ roomId ] !== undefined. What that will do is test that the value on the left isn't strictly equal to that specific undefined instance. If you're dealing with multiple windows/frames, it's possible to have different undefined instances (because each window has its own undefined). If that sounds really weird, it's because it is.
To guard against that, you usually see that comparison written as:
if (typeof this.hAreas.get( areaId )[ roomId ] !== "undefined")
...which tests that the type of the operand is "undefined" (note the quotes), which is reliable cross-window.
Try this instead:
typeof this.hAreas.get( areaId )[ roomId ] !== "undefined"