Mootools event causes infinite loop in IE7/IE8 - javascript

I have difficulties getting this to work in IE7 (and IE8).
Its a VERY reduced part of a much more complex script. So bear in mind that the methods and the structure cannot change too much.
In IE7 I get a infinite Loop when selecting one of the Types. In FF, Chrome and IE9 it works fine. It worked with mootools 1.1 Library in IE7/IE8 great too, but since I converted it to Mootools 1.4 i got that loop problem.
Maybe some kind of event delegation change in the framework. I really don't know.
Any help is greatly appreciated!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>eventz</title>
<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js" type="text/javascript"></script>
<script type="text/javascript">
var eventz = new Class({
options: {
},
initialize: function(options) {
this.setOptions(options);
this.setup();
this.jx = 0;
},
setup: function() {
this.makeEvents();
// ...
},
makeEvents : function() {
alert("init");
var finputs = $$('.trig');
finputs.removeEvents('change');
finputs.removeEvents('click');
finputs.each(function(r) {
$(r).addEvents({
'change': function(e) {
//e.preventDefault();
alert(r.name);
new Event(e).stop();
this.refresh(r); // this needs to stay as refresh calls some ajax stuff
}.bind(this)
});
}.bind(this));
// ...
},
// refresh is called from various methods
refresh : function(el) {
if(el) {
// count types checkboxes
var ob_checked = 0;
$$('.otypes').each(function(r) {
// uncheck all if clicked on "All"
if(el.id == 'typ-0') {
r.checked = false;
}
r.checked == true ? ob_checked++ : 0 ;
})
// check "All" if non selected
if(ob_checked == 0) {
$('typ-0').checked = true;
}
// uncheck "All" if some selected
if(el.id != 'typ-0' && ob_checked != 0) {
$('typ-0').checked = false;
}
// ajax call ...
}
}
});
eventz.implement(new Options);
window.addEvent('domready', function(){
c = new eventz();
});
</script>
</head>
<body>
<fieldset class="types">
<input type="checkbox" class="trig" name="otypes[]" value="0" id="typ-0" checked="checked">All
<input id="typ-14" value="14" name="otypes[]" type="checkbox" class="otypes trig">Type A
<input id="typ-17" value="17" name="otypes[]" type="checkbox" class="otypes trig">Type B
</fieldset>
</body>
</html>

Basically in MooTools 1.4.4+, change events have been 'normalized' in IE:
see this code: https://github.com/mootools/mootools-core/blob/master/Source/Element/Element.Event.js#L170-183
and this issue: https://github.com/mootools/mootools-core/issues/2170
which traces initial commits and the fixes.
With regards to your code, some changes need to take place:
new Event(e).stop(); must be rewritten to: e.stop();
implements method is now a mutator key: Implements
The whole thing can be simplified a lot. Here's a sample refactor, optimized for performance somewhat and with clearer logic.
http://jsfiddle.net/M2dFy/5/
something like:
var eventz = new Class({
options: {
},
Implements: [Options],
initialize: function(options) {
this.setOptions(options);
this.setup();
this.jx = 0;
},
setup: function() {
this.makeEvents();
// ...
},
makeEvents: function() {
var finputs = $$('.trig');
finputs.removeEvents('change');
finputs.removeEvents('click');
var self = this;
this.type0 = $('typ-0');
this.otypes = $$('.otypes');
this.pause = false; // stop flag because of IE
finputs.each(function(r) {
r.addEvents({
click: function(e) {
this.pause || self.refresh(r); // this needs to stay as refresh calls some ajax stuff
}
});
});
// ...
},
// refresh is called from various methods
refresh: function(el) {
this.pause = true;
if (el !== this.type0) {
// count types checkboxes
this.type0.set('checked', !this.otypes.some(function(other) {
return !!other.get("checked");
}));
// ajax call ...
}
else {
this.otypes.set('checked', false);
}
this.pause = false;
}
});
now, in view of the code you had, when you change .checked, it will trigger propertychange which will try to make the event bubble.
I would recommend changing all access to checked via the .set and .get methods, eg. el.set('checked', true); / el.get('checked') - similar use for id or any other property too.
Hopefully this is enough to set you on the right path, if you were to build an example of this in jsfiddle with a minimum DOM that works, I will be happy to look it over once more.
I have no IE here (mac) but I suspect it may break on clicking on a non-all checkbox as this will fire.
I would recommend moving to click events, though this will invalidate labels:
http://jsfiddle.net/M2dFy/4/

Related

Make field invisible via js code - ODOO 9

I'm looking for a method which makes a field invisible on js (i'm making a custom widget 'InvisibleIfEmptry').
I tried to override _check_visibility method when extending FormWidget.AbstractField class :
var core = require('web.core'),
form_common = require('web.form_common');
var InvisibleIfEmpty = form_common.AbstractField.extend({
start: function() {
this.on("change:effective_readonly", this, function() {
this._toggle_label();
this._check_visibility();
});
this.render_value();
this._toggle_label();
},
_check_visibility: function() {
if (this.get("effective_readonly"))
this.$el.toggleClass('o_form_invisible',true);
}
this.$el.toggleClass('o_form_invisible',false);
}
}, .....
but this makes invisible only the field's value, not the label.
my guess is to alter some of field_manager's values but i can't figure out which one ?
Thank you for your help :)
Here is my JS code for doing that :
odoo.define('myCustomModule', function(require)
{
'use strict';
var core = require('web.core'),
form_common = require('web.form_common'),
form_view = require('web.FormView');
form_common.AbstractField.include({
start: function() {
this._super();
// Check visibility logic below when content
// changes or the form swich to view mode
this.field_manager.on("view_content_has_changed", this, function() {
this._check_visibility();
});
this.on("change:effective_readonly", this, function() {
this._toggle_label();
this._check_visibility();
});
},
_check_visibility: function() {
// If the form is in view mode and the field is empty,
// make the field invisible
window.alert(this.);
if (this.field_manager.get("actual_mode") === "view" ) {
if(this.get("value") == false){
this.$el.toggleClass('o_form_invisible',true);
this.$label.toggleClass('o_form_invisible',true);
}else{
this.$el.toggleClass('o_form_invisible',this.get("effective_invisible"));
this.$label.toggleClass('o_form_invisible',this.get("effective_invisible"));
}
}else{
this.$el.toggleClass('o_form_invisible',this.get("effective_invisible"));
this.$label.toggleClass('o_form_invisible',this.get("effective_invisible"));
}
},
});
});
But this applies to all my modules.
Does Any one know how to get module/model name from AbstractField ?

Scope of variable in DOJO when created from within function

In a DOJO widget there is code in the postCreate and destroy method to create/start and stop a timer like you can see below. Depending on the value in a drop down box the timer is started or stopped. This works fine so far.
postCreate: function() {
var deferred = this.own(<...some action...>)[0];
deferred.then(
lang.hitch(this, function(result) {
this.t = new dojox.timing.Timer(result.autoRefreshInterval * 1000);
this.t.onTick = lang.hitch(this, function() {
console.info("get new data");
});
this.t.onStart = function() {
console.info("starting timer");
};
this.t.onStop = function() {
console.info("timer stopped");
};
})
);
this.selectAutoRefresh.on("change", lang.hitch(this, function(value) {
if (value == "Automatic") {
this.t.start();
} else {
this.t.stop();
}
}));
},
When leaving the page the timer is still active so I want to stop it when I leave the page using DOJOs destroy() method.
destroy: function() {
this.t.stop();
},
This however throws a this.t.stop is not a function exception. It seems like this.t is not created in the context of the widget although I use lang.hitch(this...
What am I missing here?
I solved that by just renaming the variable t to refreshTimer. Maybe t is some kind of reserved variable in Dojo?

Multiple click handlers for a single element

I've written a few events to handle opening and closing of a snap js drawer. This code below works, but I feel it could be written more efficiently. Any suggestions?
function openMobileMenu() {
event.preventDefault();
snapper.open('left');
$('#btn-menu').off('click', openMobileMenu);
$('#btn-menu').on('click', closeMobileMenu);
}
function closeMobileMenu() {
event.preventDefault();
snapper.close('left');
$('#btn-menu').on('click', openMobileMenu);
$('#btn-menu').off('click', closeMobileMenu);
}
$('#btn-menu').on('click', openMobileMenu);
Make your code modular and your concepts explicit.
You can start by creating a MobileMenu object which encapsulates the logic.
Note: The following code was not tested.
var MobileMenu = {
_snapper: null,
_$button: null,
_direction: 'left',
init: function (button, snapper, direction) {
this._$button = $(button);
this._snapper = snapper;
if (direction) this._direction = direction;
this._toggleSnapperVisibilityWhenButtonClicked();
},
_toggleSnapperVisibilityWhenbuttonClicked: function () {
this._$button.click($.proxy(this.toggle, this));
},
toggle: function () {
var snapperClosed = this._snapper.state().state == 'closed',
operation = snapperClosed? 'open' : 'closed';
this._snapper[operation](this._direction);
}
};
Then in your page you can just do the following to initialize your feature:
var mobileMenu = Object.create(MobileMenu).init('#btn-menu', snapper);
Modularizing your code will make it more maintainable and understandable in the long run, but also allow you to unit test it. You also gain a lot more flexibily because of the exposed API of your component which allows other code to interact with it.
E.g. you can now toggle the menu visibility with mobileMenu.toggle().
Use a variable to keep track of the state:
var menu_open = false;
$("#btn-menu").on('click', function(event) {
event.preventDefault();
if (menu_open) {
snapper.close('left');
} else {
snapper.open('left');
}
menu_open = !menu_open; // toggle variable
});
snap has a .state() method, which returns an object stuffed with properties, one of which is .state.
I think you want :
$('#btn-menu').on('click', function() {
if(snapper.state().state == "closed") {
snapper.open('left');
} else {
snapper.close('left');
}
});
Or, in one line :
$('#btn-menu').on('click', function() {
snapper[['close','open'][+(snapper.state().state == 'closed')]]('left');
});
Also, check How do I make a toggle button? in the documentation.

backbone.js do something when event (vent) is complete?

$('button').click(function(){
App.vent.trigger("box:change");
});
App.BoxView = Backbone.View.extend({
initialize: function(options) {
this.listenTo( App.vent, "box:change", this.alter ); // animate, etc.
},
...
});
I have a main view, in wich i wish to do some changes when (and/or):
the event is processed by all my boxes
all my boxes done with some animations
can't wrap my head around this(long work day)...
please help =)
what is the better practice?
i'm looking for something like this:
App.MainView = Backbone.View.extend({
initialize: function(options) {
// when all the events are complete
this.listenTo( App.vent, "box:change" ).onComplete( this.rearrange_stuff );
// when all the animations are complete
this.listenTo( App.animationBuffer, "box:fadeOut" ).onComplete( this.rearrange_stuff );
},
...
});
update:
and what if I have a long chain of events - complete - events - complete (not loop) in my application, what is the better way to set this queue?
with jquery I found promise, just need to figure-out how i apply this to all my views..
http://api.jquery.com/promise/
(update)
For now, I've done it this way...
http://jsfiddle.net/Antonimo/YyxQ3/2/
App.vent = _.extend(Backbone.Events, {
promise: function(name){
if(typeof this._bills[name] === "undefined"){
this._bills[name] = 0;
} else {
this._bills[name] ++;
}
},
keepPromise: function(name){
var that = this;
setTimeout( function(){
if(typeof that._checks[name] === "undefined"){
that._checks[name] = 0;
} else {
that._checks[name] ++;
}
if(typeof that._bills[name] !== "undefined"){
if( that._checks[name] >= that._bills[name] ){
that._checks[name] = 0; // reset
that._bills[name] = 0; // reset
that.trigger(name); // emit event
}
}
}, 30);
},
_bills: {},
_checks: {}
});
// usage:
alter: function() {
App.vent.promise('some:event');
// Animate, or not..
App.vent.pay('some:event');
},
I was looking for a solution to this and found this plugin to Backbone that adds a "triggerThen" method to Backbone.Events and other Backbone objects which allows you to trigger an event and then call a function after all of the event listeners have completed.
https://github.com/bookshelf/trigger-then
It would be nice if there was an official Backbone solution to this though that used promises throughout the Backbone.Events framework.

Jquery bind not working while within a javascript recursive loop

I am writing a piece of code that changes some lights on a screen from red to green randomly and waits for the user to hit the key that corresponds to the light lit.
When I run this code you are able to hit the a,d,j or l key and an alert will pop up. However, as soon as I click the start button no keys are recognised. And when the loop has finished the bind still seems to become disabled. I have tried moving the bind to other places but I have had no joy. Your help is much appreciated.
$( function() {
$('#start').bind('click', function() { main(); });
$(document).bind('keypress', function(e) { keyPress(e); } );
} );
function getRand(val) {
return Math.floor(Math.random()*val)+1;
}
function main() {
preD = new Date;
preDs = preD.getTime();
randTime=Math.floor(Math.random()*1001)+1500;
playSound();
flash();
}
function flash() {
zone = getZone();
setTimeout(function() {
$('#r'+zone).css("background-image", "url(images/rea_grn.jpg)");
setTimeout(function() {
$('#r'+zone).css("background-image", "url(images/rea_red.jpg)");
if(cond[1] < 8) {
main();
}
} , 200);
} , randTime);
}
function getZone() {
if(condition==1) {
zone = getRand(2);
if( test[1][zone] < 8 ) {
test[1][zone] += 1;
cond[1] += 1;
return zone;
} else {
getZone();
}
}
}
function keyPress(e) {
var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if (actualkey=="a" || actualkey=="d" || actualkey=="j" || actualkey=="l" ) {
dd = new Date;
reat = dd.getTime();
alert(1);
//keypressed[condition][zone]['k']=actualkey;
//keypressed[condition][zone]['t']=(reat-preDs);
}
}
The reason that this could be happening is, when you generate code dynamically or alter any existing code the bind needs to be done again, because the function to bind just runs once and only for the members already created. So when you create dynamically code, you are forced to run the binding function to recognize the new elements.
this ways is not very recommended, instead of this, you could bind a container like 'div' or something and inside of this validate which element is calling you. This will work because your container is created once and the binding is properly assigned and doesn't matter if the content of your container changes, the binding always work.
Regards
Using a jquery sound plugin was the answer.
Fixed it with this : plugins.jquery.com/project/sound_plugin

Categories

Resources