Equivalent of deprecated jQuery Toggle Event [duplicate] - toggle

This question already has answers here:
Where has fn.toggle( handler(eventObject), handler(eventObject)...) gone?
(4 answers)
Closed 9 years ago.
jQuery's Toggle Event function has been removed as part of version 1.9.
I was using this function like so:
$('#example').toggle(function() {
do stuff
}, function() {
do stuff
});
What would be the best way to reproduce this functionality now Toggle Event has gone?

Load the MIGRATE and see the code there
See my post about the same thing
Where has fn.toggle( handler(eventObject), handler(eventObject)...) gone?
I have suggested they rename it to fn.toggler instead of removing it
Here is the code - it is a self-contained jQuery plugin and can be used as is.
jQuery.fn.toggle = function( fn, fn2 ) {
// Don't mess with animation or css toggles
if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) {
return oldToggle.apply( this, arguments );
}
// migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated");
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
};
Shorter, non-tested version:
(function( $ ){
$.fn.toggler = function( fn, fn2 ) {
var args = arguments,guid = fn.guid || $.guid++,i=0,
toggler = function( event ) {
var lastToggle = ( $._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
$._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
event.preventDefault();
return args[ lastToggle ].apply( this, arguments ) || false;
};
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
};
})( jQuery );

This also works well.
$.fn.toggleClick = function(){
var functions = arguments ;
return this.click(function(){
var iteration = $(this).data('iteration') || 0;
functions[iteration].apply(this, arguments);
iteration = (iteration + 1) % functions.length ;
$(this).data('iteration', iteration);
});
};

Related

Protractor not able to execute else part of my code when element is not displayed/present

I always identify element on my screen with isDisplayed/isPresent and then add if/else to perform further test. But else part of the screen never get executed and get error like "Failed: Index out of bound. Trying to access element at index: 0, but there are only 0 elements that match locator By(css selector, .noga-selected-summary.list.ng-scope.layout-row)" on console log.
Test_PO.js is as follow,
var ProfilePO = function(){
this.Setting = element.all(by.css('.md-icon-button.md-button.md-dark-theme.md-ink-ripple')).get(1);
this.SettingSubMenus = element.all(by.css('.md-tab.ng-scope.ng-isolate-scope.md-ink-ripple'));
//this.ReqProductLabel = element(by.css('[ng-show="ngModel && ngModel.length > 0"]'));
this.BusinessPage = element(by.css('[ng-model="required_categories"]'));
this.AddProductButton = element(by.css('[ng-click="addCategory()"]'));
this.AddedProdCat = element.all(by.css('.noga-selected-summary.list.ng-scope.layout-row'));
this.DeleteAddedProd = element.all(by.css('[ng-click="removeCategory(category)"]'));};
module.exports = ProfilePO;
test_spec.js is as follow,
it('Verify user can add required products on business screen using Find Product or Service Dropdown', function() {
Profile.AddedProdCat.get(0).isDisplayed().then(function(AddedProdCatIsDisplayed){
console.log('Added Prod Cat Is Displayed: ' + AddedProdCatIsDisplayed);
if (AddedProdCatIsDisplayed) {
Profile.AddedProdCat.count().then(function(count){
var Count1 = count;
var C1 = Count1-1;
console.log('Product list has ' + count + ' products');
for (var i=0, j=0; i <= C1 ; i++) {
Profile.DeleteAddedProd.get(j).click();
console.log('deleted ' + (i+1) + ' product');
browser.sleep(2000);
}
});
} else {
FuncLib.NogaList.isDisplayed().then(function(NogaListIsDisplayed) {
console.log('Find Product or Service Dropdown Is Displayed: ' + NogaListIsDisplayed);
if (NogaListIsDisplayed) {
FuncLib.SltNogaCat("A011100"); //select Noga
Profile.AddProductButton.isDisplayed().then(function (AddProdButtonDisplayed){
console.log('Add product button is displayed: ' + AddProdButtonDisplayed);
Profile.AddProductButton.click();
browser.sleep(3000);
Profile.AddedProdCat.isDisplayed().then(function(AddedProdCatIsDisplayed){
console.log('Added Prod Cat Is Displayed: ' + AddedProdCatIsDisplayed);
expect(Profile.AddedProdCat.getText()).toEqual('A011100');
});
});
} else
console.log('Noga Catagory dropdown is not displayed');
});
}
});
});
When"added product category list" is available on screen, this script works nicely but if I don't have added product category list, it returns above mentioned error. I tried using isPresent instead of isDisplayed but still I get same error. Kindly tell me what I need to do to handle this error?
What version of protractor you are using? This should be fixed starting from 3.3.0 - https://github.com/angular/protractor/commit/bd78dfc79b1435d124c994482df6879066079a4d
I think your this.AddedProdCat takes some time to get displayed.
You can use just wait using Expected Conditions for that element, something like this -
it('Verify user can add required products on business screen using Find Product or Service Dropdown', function() {
var EC = protractor.ExpectedConditions;
browser.wait(EC.visibilityOf(Profile.AddedProdCat.get(0)), 5000);
Profile.AddedProdCat.get(0).then(function(firstElement){
console.log('Added Prod Cat firstElement: ' + firstElement);
if (firstElement) {
Profile.AddedProdCat.count().then(function(count){
var Count1 = count;
var C1 = Count1-1;
console.log('Product list has ' + count + ' products');
for (var i=0, j=0; i <= C1 ; i++) {
Profile.DeleteAddedProd.get(j).click();
console.log('deleted ' + (i+1) + ' product');
browser.sleep(2000);
}
});
}
});

Access non static function from static function

Here is some insight: I am working with UnityScript in Unity 4.6.3. I have one script called Pause.js and it contains this function:
function fadeMusicOut () {
while (audio.volume >= 0.005) {
yield WaitForSeconds(0.1);
Debug.Log("Loop Entered: " + audio.volume);
audio.volume = (audio.volume - 0.015);
}
Another script GameManager.js has this function:
static function Score (wallName : String) {
if (wallName == "rightWall") {
playerScore01 += 1;
}
else {
playerScore02 += 1;
}
if (playerScore01 == SettingsBack.scoreLimit || playerScore02 == SettingsBack.scoreLimit)
{
startParticles = 1;
SettingsBack.gameOver = 1;
BallControl.fadeSound = 1;
yield WaitForSeconds(4);
Camera.main.SendMessage("fadeOut");
Pause.fadeMusic = 1;
SettingsBack.soundVolume = 0;
yield WaitForSeconds(2);
playerScore01 = 0;
playerScore02 = 0;
SettingsBack.soundVolume = oldSoundVol;
Application.LoadLevel("_Menu");
}
}
So pretty much I want to call the fadeMusicOut() function from static function Score, but it will not let me because it says it needs an instance of that object.
The Pause.js script is not attached to any game objects, but it is attached to 2 buttons that call their specific functions. The GameManager.js script is attached to an object called GM. So how can I go about calling fadeMusicOut() from the Score function?
I have tried setting new vars that import the game object but still no luck. I tried making fadeMusicOut() a static function, but it creates many errors.
Any help at all is appreciated.

easeljs cannot dispatch event

I want to dispatch my event,but it doesn't work. this is my code and I've deleted some irrelevant parts .
(function(window){
function HeroSelectView(){
this.initialize();
}
createjs.EventDispatcher.initialize(HeroSelectView.prototype);
HeroSelectView.prototype = new createjs.Container();
var selectedName;
HeroSelectView.prototype.Container_initialize=HeroSelectView.prototype.initialize;
HeroSelectView.prototype.initialize=function(){
this.Container_initialize();
this.initView();
}
HeroSelectView.prototype.initView = function(){
for (var i = 0; i < heroArray.length; i++) {
heroArray[i].x=100+40*i;
heroArray[i].y=200;
this.addChild(heroArray[i]);
heroArray[i].addEventListener("click",onSelectHero);
};
}
function onSelectHero(event){
selectedName=event.target.name;
var myevent = {
type: "selectedEvent",
param: selectedName
};
//var myevent=new createjs.Event("selectedEvent"); //createjs 0.7 doesnot work either.
this.dispatchEvent(myevent);
}
window.HeroSelectView=HeroSelectView;
}(window))
in the onSelectedHero, at first I tried it with createjs-0.61. you can see the "myevent" .But there is an error " TypeError: Argument 1 of EventTarget.dispatchEvent is not an object.". Then I tried it with version 0.7, but still got the same error. How can I fix this?
Thanks

How can i force website to stay in frame?

I'm using Firefox + searchbastard addon to do a multi-search on shopping search engines.The pages are part of a frame. This works just fine for all sites I tried so far except for shopmania.com.
If I use noscript to forbid scripts from the shopmania domain name then everything stays in place but the part of the website elements become nonresponsive. I know there is an option in Firefox to force links that open in a new window to open in a new tab. Is there something similar to prevent websites from popping out of frame? Maybe a Firefox addon that blocks these requests?
Or at least can someone please tell me what is causing only this website to act like this?
EDIT: What tool can i use to pause firefox OR javascript and stepthrough code like in c++ ? I tried a javascript debugger and firebug. They don't help but i'm probably not using them right..
EDIT2: I tried this greasemonkey script : https://userscripts.org/scripts/show/92424. It does not work so i guess it isn't because of 'target' attribute
This is wrong. I'm guessing you're using a plugin to capture and override the output some site gives you. I'm pretty sure this violates their ToS and it's not a very nice thing to do in general.
JavaScript is not designed to allow this kind of meddling. It's patchy at best.
If you want to use the data from a website, to aggregate or display in some manner, use their public API. If they don't have a public API they probably don't want you to use their service in such a manner.
The solution : I took the script from Stop execution of Javascript function (client side) or tweak it and modified it to search for the tag that has in it top.location = location and then appended a new script with the if (top != self) {top.location = location;} line commented . Being a js total newbie i don't know if it's the most elegant choice but it soves the prob. Special thanks to Tim Fountain.
I will leave this open just in case someone else will suggest a better solution, for my and others's education. Again thanks for the help.
Below is the code:
// ==UserScript==
// #name _Replace evil Javascript
// #run-at document-start
// ==/UserScript==
/****** New "init" function that we will use
instead of the old, bad "init" function.
*/
function init () {
/* //changing stuff around here
var newParagraph = document.createElement ('p');
newParagraph.textContent = "I was added by the new, good init() function!";
document.body.appendChild (newParagraph); */
<!--//--><![CDATA[//><!--
document.getElementsByTagName("html")[0].className+=" js "+(navigator.userAgent.toLowerCase().indexOf("webkit")>=0?"webkit":navigator.userAgent.toLowerCase().indexOf("opera")>=0?"opera":"");
for(i in css3_tags="abbr|header|footer".split("|")){document.createElement(css3_tags[i]);}
var PATH = "http://www.shopmania.com";
var PATH_STATIC = "http://im4.shopmania.org";
var PATH_SELF = "http://www.shopmania.com/";
var RETURN = "http%3A%2F%2Fwww.shopmania.com%2F";
var DOMAIN_BASE = "shopmania.com";
var SUBDOMAINS_FORCE_FILES_JS = "aff.remote,biz.remote,my.remote,cp.remote,cp.register_quick,cp.account_details,partner.remote,site.recommend,site.remote,site.feedback,site.report_problem,site.report,site.cropper";
var URL_REWRITE_MAPPING_JS = "cmd,section,do,option|feed,mode,option|forgot,section|info,page|login,section|logout,section|new_password,section,code|settings,section|shopping,param_main,param_sec|site,store_str_key|register,section|unsubscribe,section|agentie,store_str_key,id|brand,manuf_str_key|brands,letter|build,type,param_main,param_sec|compare,online|confirm,section|edit,section|deal,deal|dictionary,online|home,section|link_accounts,section|profile,user|reactivate,section|searches,letter|signup,section|rs_agent,store_str_key|rs_list,param_main,param_sec|rs_view,ad|agents,state|complex_list,param_main|complex_view,complex|list,cat|ad,a|map,option|my_ads,section|my_alerts,section";
var SVR_SITE_ID = "us";
var CONTEXT = "c5b27de70340c97a94092a43bd34b2b8";
var link_close = "Close";
var txt_loading = "Loading...";
var form_is_submitted = 0;
var search_is_focused = 0;
// Overlay object
var OL;
var DB;
var iframe_cnt = "";
// Facebook post to user's Wall action
var FACEBOOK_WALL_FEED_SIGNUP = "";
var SITENAME = "ShopMania";
//if (top != self) {top.location = location;} // SIT!
var comps = new Array(); comps['all'] = 0;var comps_cat_titles = new Array(); var views = new Array(); views['auto'] = 0; views['prod'] = 0; views['realestate'] = 0; views['classifieds'] = 0; views['all'] = 0; var search = new Array(); search['all'] = 0; search['prod'] = 0;
var favs = new Array(); favs['all'] = 0; favs['prod'] = 0; favs['store'] = 0; favs['manuf'] = 0; favs['other'] = 0; favs['realestate'] = 0; favs['auto'] = 0;
function addCss(c){var b=document.getElementsByTagName("head")[0];var a=document.createElement("style");a.setAttribute("type","text/css");if(a.styleSheet){a.styleSheet.cssText=c}else{a.appendChild(document.createTextNode(c))}b.appendChild(a)};
addCss(".lzl {visibility: hidden;}");
var RecaptchaOptions = { theme : 'clean' };
//--><!]]>
}
/*--- Check for bad scripts to intercept and specify any actions to take.
*/
checkForBadJavascripts ( [
[false, /top.location = location/, function () {addJS_Node (init);} ]
] );
function checkForBadJavascripts (controlArray) {
/*--- Note that this is a self-initializing function. The controlArray
parameter is only active for the FIRST call. After that, it is an
event listener.
The control array row is defines like so:
[bSearchSrcAttr, identifyingRegex, callbackFunction]
Where:
bSearchSrcAttr True to search the SRC attribute of a script tag
false to search the TEXT content of a script tag.
identifyingRegex A valid regular expression that should be unique
to that particular script tag.
callbackFunction An optional function to execute when the script is
found. Use null if not needed.
*/
if ( ! controlArray.length) return null;
checkForBadJavascripts = function (zEvent) {
for (var J = controlArray.length - 1; J >= 0; --J) {
var bSearchSrcAttr = controlArray[J][0];
var identifyingRegex = controlArray[J][1];
if (bSearchSrcAttr) {
if (identifyingRegex.test (zEvent.target.src) ) {
stopBadJavascript (J);
return false;
}
}
else {
if (identifyingRegex.test (zEvent.target.textContent) ) {
stopBadJavascript (J);
return false;
}
}
}
function stopBadJavascript (controlIndex) {
zEvent.stopPropagation ();
zEvent.preventDefault ();
var callbackFunction = controlArray[J][2];
if (typeof callbackFunction == "function")
callbackFunction ();
//--- Remove the node just to clear clutter from Firebug inspection.
zEvent.target.parentNode.removeChild (zEvent.target);
//--- Script is intercepted, remove it from the list.
controlArray.splice (J, 1);
if ( ! controlArray.length) {
//--- All done, remove the listener.
window.removeEventListener (
'beforescriptexecute', checkForBadJavascripts, true
);
}
}
}
/*--- Use the "beforescriptexecute" event to monitor scipts as they are loaded.
See https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
Note that it does not work on acripts that are dynamically created.
*/
window.addEventListener ('beforescriptexecute', checkForBadJavascripts, true);
return checkForBadJavascripts;
}
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
//--- Don't error check here. if DOM not available, should throw error.
targ.appendChild (scriptNode);
}
there are some escaping issues with the cdata part in the code.So SO does not allow me to post the code.
EDIT: fixed

flash_as3_facebook_api: how to iterate over FacebookSession object that is returned by FacebookDesktop.login

in flashbuilder debugger mode, I can examine all the props/vals of the FacebookSession object returned by FacebookDesktop.login when I place a breakpoint in my loginhandler method.
however, I cannot seem to iterate through the FacebookSession object using for...in. I have checked to see if the FacebookSession is dynamic using ObjectUtil.isDynamicObject(...), but it is not, so a for..in should work.
public function gf_handle_facebook_login_return( argl_success : Object ,
argl_failure : Object ) : void
{ // IF I ADD breakpoint here, I get a fully populated argl_success object in flashbuilder's Debugger Variables tab.
trace( "gf_handle_facebook_login_return , A : " + typeof( argl_success ) + " , " + argl_success[ "uid" ] ) ; // works
trace( "gf_handle_facebook_login_return , C : " + ObjectUtil.isDynamicObject( argl_success ) ) ; // false ... is NOT a dynamic class
var lvo_FBS : FacebookSession = FacebookSession ( argl_success ) ; // tried it with and without casting
var lvn_prop :* ;
for ( lvn_prop in lvo_FBS)
{ trace( "gf_handle_facebook_login_return , D : " + lvn_prop ) ; // is never called
}
for each( lvn_prop in lvo_FBS)
{ trace( "gf_handle_facebook_login_return , E : " + lvn_prop ) ; // is never called
}
}
For in will only loop through dynamic properties and as you said it is not a dynamic.
Try this example
//Get an XML description of this class
//and return the variable types as XMLList with e4x
var varList:XMLList = flash.utils.describeType(myVO)..variable;
for(var i:int; i < varList.length(); i++){
//Show the name and the value
trace(varList[i].#name+':'+ myVO[varList[i].#name]);
}