PDA

View Full Version : Restrict onclick method to be clicked only once



chot2
24 Dec 2011, 11:04 AM
Hello Guys ,

I m pretty new to JS and EXTJS . In my application we are using div as button Ext.get('editEventTime').on('click', function(e){ } . When I click on the div a window gets opened. But unfortunately this happens with a delay . In the mean while if I click on the div once again , I get two windows opened . I have already checked the condition whether the window was opened if (!win) { } but still that doesn't seem to work Is there way to restrict div to get disable once it gets clicked or making only once instance of window getting opened .

skirtle
24 Dec 2011, 7:58 PM
The single config option can be used to ensure that the listener will only ever be called once. This may be too extreme in your case if you want the element to remain reclickable after the window is closed.

The technique you describe, using an if (!win) { } check, should work fine if you've implemented it correctly.

chot2
24 Dec 2011, 9:41 PM
thanks skirtle for the repl y . I guess I have implemened i correctly .


Ext.get('editEventTime').on('click', function(e){
var win ;





if (count === false){

count = true;
console.log(count);



//var day = Ext.getDom('event_day').innerHTML;
start_date = Ext.getDom('event_startdate').innerHTML;
end_date = Ext.getDom('event_enddate').innerHTML;
var eventschetitle = Ext.getDom('event_schedule').innerHTML;
(eventschetitle == "") ? eventschetitle = "When" : eventschetitle;
var currentDt = Ext.getDom('currentDate').value;
var nxtMnthDt = Ext.getDom('nxtMonthDate').value;

//Defualt Time zone
var rightNow = new Date();
var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
var temp = date1.toUTCString();
var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")));
var temp = date2.toUTCString();
var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")));
var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);

//new time zone
eventtiming = Ext.getDom('event_time').innerHTML;
var zoneTxt;
var eventtimingGMT;
if(eventtiming == 'Eastern Time'){
eventtiming = "Eastern Time (USA)";
eventtimingGMT = "";
usZoneFlag = false;
worldZoneFlag = true;
} else if(eventtiming == 'Central Time'){
eventtiming = "Central Time (USA)";
eventtimingGMT = "";
usZoneFlag = false;
worldZoneFlag = true;
} else if(eventtiming == 'Mountain Time'){
eventtiming = "Mountain Time (USA)";
eventtimingGMT = "";
usZoneFlag = false;
worldZoneFlag = true;
} else if(eventtiming == 'Pacific Time'){
eventtiming = "Pacific Time (USA)";
eventtimingGMT = "";
usZoneFlag = false;
worldZoneFlag = true;
} else if(eventtiming == ''){
eventtiming = "Eastern Time (USA)";
eventtimingGMT = "";
usZoneFlag = false;
worldZoneFlag = true;
} else {
eventtimingGMT = eventtiming;
eventtiming = "";
usZoneFlag = true;
worldZoneFlag = false;
}

if(usZoneFlag == false){
zoneTxt = "World time zones";//view - as per prashanth comments
} else {
zoneTxt = "US time zones";//view - as per prashanth comments
}

start_hour = Ext.getDom('event_starthour').innerHTML;
start_min = Ext.getDom('event_startmin').innerHTML;
start_ampm = Ext.getDom('event_startampm').innerHTML;
end_hour = Ext.getDom('event_endhour').innerHTML;
end_min = Ext.getDom('event_endmin').innerHTML;
end_ampm = Ext.getDom('event_endampm').innerHTML;
eventcity = Ext.getDom('event_place').innerHTML;
var minStartDate=currentDt;
var minEndDate=currentDt;
//var win;
if (!win) {
var form = Ext.widget('form', {
border: false,
cls:"popup-panel",
fieldDefaults: {
labelSeparator:'',
labelStyle: 'font-weight:bold;padding-top:10px;color:#58595B;'
},
items: [ {
xtype: 'textfield',
anchor: '60%',
fieldLabel: 'Section Label',
name: 'EventScheTitle',
id:"Title",
cls:'popup-title-bgcolor',
maxLength: 20,
//allowBlank: false,
regex: /[a-zA-Z0-9]+/,
regexText:"Please remove empty spaces before or after the title",
value: eventschetitle,
listeners: {
afterrender: function(field) {
field.focus(false, 1000);
}
}
},{
xtype: 'fieldcontainer',
fieldLabel: 'Event Starts',
layout: 'hbox',
padding:'0 10 0 10',
items: [


{
xtype: 'combo',
fieldLabel: '',
labelWidth: 40,
width: 40,
name:'start_ampm',
id:'start_ampm',
editable : false,
displayField: 'label',
value:(start_ampm == '') ? 'PM' : start_ampm,
emptyText:(start_ampm == '') ? 'PM' : start_ampm,
store: Ext.create('Ext.data.Store', {
fields: ['label'],
sorters: 'type',
proxy : {
type: 'memory',
data : [{label: 'AM'},{label: 'PM'}]
}
})
}
]
}





],
buttons: [{

text: 'Save',
handler: function() {
var form = this.up('form').getForm();
if (form.isValid()) {
hideStartDate = Ext.getCmp('hide_StartDate').getValue();
hideEndDate = Ext.getCmp('hide_EndDate').getValue();
eventschetitle = Ext.String.trim(this.up('form').getForm().getValues()['EventScheTitle']);
//removing "<" and ">" from the sting
eventschetitle = replaceTags(eventschetitle);
(eventschetitle == "") ? eventschetitle = "When" : eventschetitle;
//time zone
if(usZoneFlag == false){
var usTimeZone = form.getValues()['us_time_zone'];
(usTimeZone == undefined) ? usTimeZone = 'Eastern Time (USA)' : usTimeZone;
if(usTimeZone == 'Eastern Time (USA)'){
eventtiming = "Eastern Time";
} else if(usTimeZone == 'Central Time (USA)'){
eventtiming = "Central Time";
} else if(usTimeZone == 'Mountain Time (USA)'){
eventtiming = "Mountain Time";
} else if(usTimeZone == 'Pacific Time (USA)'){
eventtiming = "Pacific Time";
}
} else {
var worldTimeZone = form.getValues()['world_time_zone'];
var startIndex = worldTimeZone.indexOf('(');
var endIndex = worldTimeZone.indexOf(')');
eventtiming = worldTimeZone.substring(startIndex+1,endIndex);
}

if(Ext.query("fieldset")[Ext.query("fieldset").length-1].className=='x-fieldset x-fieldset-collapsed x-fieldset-default')
{
is_repeat = false;
repeat_collapse = true;
}
else if(Ext.query("fieldset")[Ext.query("fieldset").length-1].className=='x-fieldset x-fieldset-default')
{
is_repeat = true;
repeat_collapse = false;
}
else{
repeat_collapse = true;
is_repeat = false;
}
var repeatEventStatus = form.getValues()['EventStatus'];
repeatData = [];
if(repeatEventStatus==0)
{
schedule_month = '';
repeat_mode= 'daily';
untill_date = form.getValues()['dialy_date'];
if(untill_date == undefined){
untill_date = '';
}//else{d_untill_date = untill_date;}
var dialy_occurance = form.getValues()['dialy_occurance'];
if(dialy_occurance==0)
{
if(Ext.getDom('dialy_occurance_value')){
occur_mode_evry = Ext.getDom('dialy_occurance_value').value;
}
repeatData[0] = {id:0,name:"mon"};
}
else
{
occur_mode_evry = "1";
repeatData[0] = {id:0,name:"mtf"};
}
next_start_date = '';
next_end_date = '';
startTime = '';
endTime = '';
}
else if(repeatEventStatus==1)
{
schedule_month = '';
repeat_mode ='weekly';
untill_date = form.getValues()['weekly_date'];
if(untill_date == undefined){
untill_date = '';
}//else{w_untill_date = untill_date;}
occur_mode_evry = Ext.getDom('weekly_occurance').value;
var selectedDays = this.up('form').getForm().getValues()['wkly'];
if(selectedDays == undefined && !repeat_collapse){
Ext.Msg.alert("Alert","Select at least one day in the week");
return false;
}else if(selectedDays != undefined && repeat_collapse){
for(var n=0;n<selectedDays.length;n++){
var selectedValue = selectedDays[n];
var selectedValueArray = selectedValue.split('.');
repeatData[n] = {id:selectedValueArray[0],name:selectedValueArray[1]};
}
}
next_start_date = '';
next_end_date = '';
startTime = '';
endTime = '';
}
else if(repeatEventStatus==2)
{
repeat_mode ='monthly';
untill_date = form.getValues()['monthly_date'];
if(untill_date == undefined){
untill_date = '';
}
occur_mode_evry = Ext.get('monthly_shedule').getValue();
if(form.getValues()['monthly_occurance'] == 0){
repeatData[0] = {"wk_day":Ext.get('monthly_occurance_input').getValue()};
schedule_month = 'day';
}
if(form.getValues()['monthly_occurance'] == 1){
repeatData[0] = {"wk_day":Ext.get('indexOfDay').getValue(),"wh_day":Ext.get('dayOfMonth').getValue()};
schedule_month = 'weekday';
}
next_start_date = '';
next_end_date = '';
startTime = '';
endTime = '';
}
else if(repeatEventStatus==3)
{
repeat_mode ='others';
schedule_month = '';
occur_mode_evry="1";
untill_date = form.getValues()['otherEndDate'];
if(untill_date == undefined){
untill_date = '';
}
next_start_date = form.getValues()['otherStartDate'];
start_date = next_start_date;
next_end_date = form.getValues()['otherEndDate'];
end_date = next_end_date;
startTime = form.getValues()['otherStartHours']+':'+form.getValues()['otherStartMins']+" "+form.getValues()['otherStartAmpm'];
start_time = startTime;
endTime = form.getValues()['otherEndHours']+':'+form.getValues()['otherEndMins']+" "+form.getValues()['otherEndAmpm'];
end_time = endTime;
repeatData[0] = {"wk_day":""};
/*repeatInfo = {repeat_mode:'others', next_start_date:startDt, next_end_date:endDt, start_time:startTime, end_time:endTime, occur_mode_evry:"1"};*/
}
if(untill_date.length<=0 && is_repeat){
Ext.Msg.alert("Alert","Please select untill date for event.");
return false;
}
start_hour = (form.getValues()['start_hour'] == undefined) ? '1' : form.getValues()['start_hour'];
start_min = (form.getValues()['start_min'] == undefined) ? '00' : form.getValues()['start_min'];
start_ampm = (form.getValues()['start_ampm'] == undefined) ? 'AM' : form.getValues()['start_ampm'];
start_time = start_hour+':'+start_min+' '+start_ampm;
end_hour = (form.getValues()['end_hour'] == undefined) ? '4' : form.getValues()['end_hour'];
end_min = (form.getValues()['end_min'] == undefined) ? '00' : form.getValues()['end_min'];
end_ampm = (form.getValues()['end_ampm'] == undefined) ? 'AM' : form.getValues()['end_ampm'];
end_time = end_hour+':'+end_min+' '+end_ampm;
start_date = form.getValues()['start_date'];
end_date = form.getValues()['end_date'];
total_starttime = start_date+' '+start_time;
total_endtime = end_date+' '+end_time;
var v_start_hour;
if(start_ampm == 'PM' && start_hour*1 < 12){
v_start_hour = (start_hour*1)+12;
}
if(start_ampm == 'AM' && start_hour*1 == 12){
v_start_hour = (start_hour*1)-12;
}
if(start_ampm == 'AM' && start_hour*1 < 12){
v_start_hour = start_hour*1;
}
if(start_ampm == 'PM' && start_hour*1 == 12){
v_start_hour = start_hour*1;
}
if(end_ampm == 'PM' && end_hour*1 < 12){
v_end_hour = (end_hour*1)+12;
}
if(end_ampm == 'AM' && end_hour*1 < 12){
v_end_hour = end_hour*1;
}
if(end_ampm == 'AM' && end_hour*1 == 12){
v_end_hour = (end_hour*1)-12;
}
if(end_ampm == 'PM' && end_hour*1 == 12){
v_end_hour = end_hour*1;
}
var count = 0;
var v_start_time = Ext.Date.format(new Date(start_date), "M d, Y")+' '+v_start_hour+':'+start_min;
console.log('start time '+ v_start_time);

v_end_hour = Ext.Date.format(new Date(end_date), "M d, Y")+' '+v_end_hour+':'+end_min;
console.log('endtime '+ v_end_hour);
if(new Date(v_start_time) > new Date(v_end_hour)){

Ext.Msg.alert("Alert","Event start date & time should not be greater than the event end date & time for the event");
return false;
}
if(new Date(v_start_time).getTime() < new Date().getTime()){
count ++;
console.log(count)
console.log('executed')
console.log(new Date(v_start_time).getTime())
console.log(new Date().getTime())

Ext.Msg.alert("Alert","Event can not be created in past");
return false;
}
var utDate = new Date();
if(untill_date != '' && is_repeat){
utDate = new Date(untill_date);
if(utDate.getTime() < new Date(v_end_hour).getTime()){
Ext.Msg.alert("Alert","Untill date for repeat event should be greater than the event end date.");
return false;
}
}
//formatting the date to display
Ext.getDom('event_startdate').innerHTML= Ext.Date.format(new Date(start_date), "M d, Y");
Ext.getDom('event_enddate').innerHTML= Ext.Date.format(new Date(end_date), "M d, Y");
Ext.getDom('event_starthour').innerHTML= start_hour;
Ext.getDom('event_startmin').innerHTML= start_min;
Ext.getDom('event_startampm').innerHTML= start_ampm;
Ext.getDom('event_endhour').innerHTML= end_hour;
Ext.getDom('event_endmin').innerHTML= end_min;
Ext.getDom('event_endampm').innerHTML= end_ampm;
Ext.getDom('event_time').innerHTML=eventtiming;//(eventtiming=='') ? "GMT "+hoursDiffStdTime : eventtiming;
Ext.getDom('event_schedule').innerHTML= eventschetitle;
whenFlag = true;
Ext.getDom('editEventTime').innerHTML = "Edit";
Ext.getDom('editEventTime').className = "right edit-button marginRight0";
form.reset();
this.up('window').hide();
Ext.getDom('normal_address').style.display="none";
Ext.getDom('edit_address').style.display="block";
}

//clearing id zoneTextToggle for timezone
var zoneIdQuery = Ext.query('div[id="zoneTextToggle"]');
Ext.each(zoneIdQuery,function(){
this.id = "";
});
}
}, {
text: 'Cancel',
handler: function() {
//clearing id zoneTextToggle for timezone
var zoneIdQuery = Ext.query('div[id="zoneTextToggle"]');
Ext.each(zoneIdQuery,function(){
this.id = "";
});

this.up('form').getForm().reset();
this.up('window').hide();
}
}]
});

if(hideEndDate){
Ext.getCmp('hide_EndDate').setValue(hideEndDate);
}if(hideStartDate){
Ext.getCmp('hide_StartDate').setValue(hideStartDate);
}
win = Ext.widget('window', {

title: 'Event When',
closeAction: 'hide',
width: 520,
layout: 'fit',
animateTarget: 'editEventTime',
resizable: false,
modal: true,
items: form
});


}
win.show();

//var titleTxt = Ext.getDom('eventTime').innerHTML;
/*Ext.MessageBox.show({
title: 'Edit Event Timing',
msg: 'Please enter your event timings:',
value: titleTxt,
width:350,
buttons: Ext.MessageBox.OKCANCEL,
fn: saveTitle,
defaultTextHeight: 100,
multiline: true,
animateTarget: 'editEventTime'
});
function saveTitle(btn,txt,opt){
if(btn == 'ok' && txt != ''){
Ext.getDom('eventTime').innerHTML = txt;
} else if(btn == 'ok' && txt == ''){
Ext.MessageBox.show(opt);
} else {
txt = '';
}
}*/

console.log(count)
}

});


Can you please let me know how can I creae single instance of window as told here
http://www.sencha.com/forum/showthread.php?156464-Multiple-clicks-in-the-button-produces-multiple-window-instances

Any working exps of that sort ?
...

chot2
24 Dec 2011, 9:43 PM
Link for it .
http://www.sencha.com/forum/showthread.php?156464-Multiple-clicks-in-the-button-produces-multiple-window-instances

skirtle
24 Dec 2011, 9:56 PM
That won't work. Simplifying your example you have this:


Ext.get('editEventTime').on('click', function(e){
var win;

if (!win) {
...
}
});

The variable win is not shared between invocations, it'll always be undefined.

There are various way to work around this, such as using a component query to grab the window instead. If you do want to stick with the win approach you'll need to move it outside the function. As global variables are evil, you'll still want to make sure it's wrapped in a suitable function. Chances are you're code is already in such a function but by way of an example of keeping win scoped as minimally as possible:


(function() {
var win;

Ext.get('editEventTime').on('click', function(e){
if (!win) {
...
}
});
})();

Note that the outer function is invoked immediately.

chot2
24 Dec 2011, 10:26 PM
Awesome =D>Thanks buddy that has worked for me \:D/. I m sorry I couldn't understand the difference can you please explain me in detail the difference between declaring it globally and locally or can you please let me know where I can find information about that :)

skirtle
24 Dec 2011, 11:03 PM
There's plenty of info about this to be found via Google. Rather than writing a detailed explanation I'll just give you enough to know what to search for...

The first concept to understand is scope. Most languages have block scope but JavaScript does not. Instead variables are scoped to functions. This is not to be confused with the ExtJS concept of scope, which is an entirely different concept and isn't relevant to this.

The second concept is the keyword var. This declares a variable to be local to the current function, rather than global. You should almost always use var. However, if you aren't inside a function then using var won't help, your variable will still be global.

The third concept is closures. Declaring win outside of the handler function forms a closure on the variable.

These are all really important core concepts in JavaScript. Trying to write ExtJS code without a grasp of these kinds of things will be very difficult. I highly recommend getting a good book on JavaScript and reading it, you'll be glad you did.

chot2
28 Dec 2011, 2:01 AM
skirtle

Can you please let me know what are the other ways to handle this :)