YUI Event Utility problem - javascript

I create a button, when clicked, it activates a backup feature.
My problem, backup is launched before I have clicked to this button.
How, do I fix this problem ? Any Idea ?
Here is my code (fragment) :
(button) :
var oSaveCuratedQuery = new YAHOO.widget.Button({
type: "button",
label: "Save Query",
id: "updateCuratedQuery",
name: "updateCuratedQuery",
value: "updateCuratedQueryValue",
container: idReq });
YAHOO.util.Event.addListener("updateCuratedQuery-button", "click", saveCuratedQuery(idReq, contentCurValue));
(backup function) :
function saveCuratedQuery (geneId,curatedText) {
var handleSuccessGeneQueries = function(o){
Dom.get('progress').innerHTML = "Data Saved...";
}
var handleFailureGeneQueries = function(o){
alert("Save failed...")
}
var callbackGeneQueries =
{
success:handleSuccessGeneQueries,
failure: handleFailureGeneQueries
};
var sUrlUpdate = "save.html?";
var postData = 'key=saveCuratedQuery&value=gene_id==' +geneId+ '--cq==' +curatedText;
var request = YAHOO.util.Connect.asyncRequest('POST', sUrlUpdate, callbackGeneQueries, postData);
}
I also try :
oSaveCuratedQuery.on("click",saveCuratedQuery(idReq, contentCurValue));
But same problem !
The backup is done before I click "save" button.
Thank you for help.

The third argument of addListener should be a function to be run when the event happens.
You are passing it the return value of saveCuratedQuery instead.
var callbackSaveCuratedQuery = function (idReq, contentCurValue) {
return function callbackSaveCuratedQuery () {
saveCuratedQuery(idReq, contentCurValue);
};
}(idReq, contentCurValue); // Use an anonymous closure function
// to ensure that these vars
// do not change before the click
// event fires.
YAHOO.util.Event.addListener("updateCuratedQuery-button",
"click",
callbackSaveCuratedQuery
);
See https://developer.mozilla.org/en/A_re-introduction_to_JavaScript#Closures if you need to learn about closures.

Related

ExtJS handler in button

I have a question about simple button.
Below definition:
var table = null;
var buttonConfig = {
buttonId: 'mybutton1',
text: 'Template button',
icon: 'style/img/fam/button.png',
tooltip: 'template button',
handler: function () {
var someConfig = null;
fileProcessing(someButton, someConfig);
}
};
addButtonToGrid(table, buttonConfig);
Function called fileProcessing has 2 args - someButton and someConfig.
I want to pass in someButtton, the button from object buttonConfig. How should I do it ?
Thanks for any advice
You can do it like below:
handler: function () {
var someConfig = null;
var someButton = this;
fileProcessing(someButton, someConfig);
}
Reference
PARAMETERS
button : Ext.button.Button
This button.
e : Ext.event.Event
The click event.
Hope this will help/guide you.

How to execute a function when clicking an area inside an object?

I created an object with map Areas by using DOM-Elements. Now I want to execute a function when clicked on an area(coordinates). I think I also Need to check the area if it is clicked or not ? Also I think I'm missing something on the DOM-Element.
var _images = { //Object-MapArea
start: {
path: 'start.jpg',
areas: [{
coords: '18,131,113,140',
text: 'Homepage',
onclick: doSomething, // ???
}]
},
}
// ..... there is more code not shown here
//Creating DOM-Elements
var areaElem = document.createElement('AREA');
// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");
areaElem.onclick = doSomething; ? ? ?
if (element.captureEvents) element.captureEvents(Event.CLICK); ? ? ?
areaElem.addEventListener('click', onArea_click);
_map.appendChild(areaElem);
function doSomething(e) {
if (!e) var e = window.event
e.target = ... ? ?
var r = confirm("Data will get lost!");
if (r == true) {
window.open("homepage.html", "_parent");
} else {
window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?
}
}
See the comments I added to your code ;)
var _images = { //Object-MapArea
start: {
path: 'start.jpg',
areas: [{
coords: '18,131,113,140',
text: 'Homepage',
clickHandler: doSomething // I changed the name to avoid confusion but you can keep onclick
}]
},
}
// ..... there is more code not shown here
//Creating DOM-Elements
var areaElem = document.createElement('AREA');
// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");
// Add a listener on click event (using the function you defined in the area object above)
areaElem.addEventListener('click', area.clickHandler);
// Add your other click handler
areaElem.addEventListener('click', onArea_click);
_map.appendChild(areaElem);
function doSomething(e) {
// Get the area clicked
var areaClicked = e.target;
// I dont understand the following code...
var r = confirm("Data will get lost!");
if (r == true) {
window.open("homepage.html", "_parent");
} else {
window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?
}
}
Hope it helps ;)
I think I also Need to check the area if it is clicked or not
You are creating an element areaElem and attaching event to the same dom.
So there may not be need of any more check
You may not need to add both onclick & addEventListner on same element and for same event. Either onclick function or addEventListener will be sufficient to handle the event.
areaElem.onclick = function(event){
// Rest of the code
// put an alert to validate if this function is responding onclick
}
areaElem.addEventListener('click', onArea_click);
function onArea_click(){
// Rest of the code
}

jQuery plugin instances variable with event handlers

I am writing my first jQuery plugin which is a tree browser. It shall first show the top level elements and on click go deeper and show (depending on level) the children in a different way.
I got this up and running already. But now I want to implement a "back" functionality and for this I need to store an array of clicked elements for each instance of the tree browser (if multiple are on the page).
I know that I can put instance private variables with "this." in the plugin.
But if I assign an event handler of the onClick on a topic, how do I get this instance private variable? $(this) is referencing the clicked element at this moment.
Could please anyone give me an advise or a link to a tutorial how to get this done?
I only found tutorial for instance specific variables without event handlers involved.
Any help is appreciated.
Thanks in advance.
UPDATE: I cleaned out the huge code generation and kept the logical structure. This is my code:
(function ($) {
$.fn.myTreeBrowser = function (options) {
clickedElements = [];
var defaults = {
textColor: "#000",
backgroundColor: "#fff",
fontSize: "1em",
titleAttribute: "Title",
idAttribute: "Id",
parentIdAttribute: "ParentId",
levelAttribute: "Level",
treeData: {}
};
var opts = $.extend({}, $.fn.myTreeBrowser.defaults, options);
function getTreeData(id) {
if (opts.data) {
$.ajax(opts.data, { async: false, data: { Id: id } }).success(function (resultdata) {
opts.treeData = resultdata;
});
}
}
function onClick() {
var id = $(this).attr('data-id');
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, id);
}
function handleOnClick(parentContainer, id) {
if (opts.onTopicClicked) {
opts.onTopicClicked(id);
}
clickedElements.push(id);
if (id) {
var clickedElement = $.grep(opts.treeData, function (n, i) { return n[opts.idAttribute] === id })[0];
switch (clickedElement[opts.levelAttribute]) {
case 1:
renderLevel2(parentContainer, clickedElement);
break;
case 3:
renderLevel3(parentContainer, clickedElement);
break;
default:
debug('invalid level element clicked');
}
} else {
renderTopLevel(parentContainer);
}
}
function getParentContainer(elem) {
return $(elem).parents('div.myBrowserContainer').parents()[0];
}
function onBackButtonClick() {
clickedElements.pop(); // remove actual element to get the one before
var lastClickedId = clickedElements.pop();
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, lastClickedId);
}
function renderLevel2(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderLevel3(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderTopLevel(parentContainer) {
parentContainer.html('');
var browsercontainer = $('<div>').addClass('fct-page-pa fct-bs-container-fluid pexPAs myBrowserContainer').appendTo(parentContainer);
// rendering the top level display
}
getTreeData();
//top level rendering! Lower levels are rendered in event handlers.
$(this).each(function () {
renderTopLevel($(this));
});
return this;
};
// Private function for debugging.
function debug(debugText) {
if (window.console && window.console.log) {
window.console.log(debugText);
}
};
}(jQuery));
Just use one more class variable and pass this to it. Usually I call it self. So var self = this; in constructor of your plugin Class and you are good to go.
Object oriented way:
function YourPlugin(){
var self = this;
}
YourPlugin.prototype = {
constructor: YourPlugin,
clickHandler: function(){
// here the self works
}
}
Check this Fiddle
Or simple way of passing data to eventHandler:
$( "#foo" ).bind( "click", {
self: this
}, function( event ) {
alert( event.data.self);
});
You could use the jQuery proxy function:
$(yourElement).bind("click", $.proxy(this.yourFunction, this));
You can then use this in yourFunction as the this in your plugin.

OpenLayers - how to use single and double click event on feature

I am using Opnelayers control for selection of feature
OpenLayers.Control.SelectFeature
when I triggered the single click event then feature get selected and its working fine for me. Now I want to use double click event for another operation.
I have get the idea from this link feature to have both a single click and double click event?
I have used the same code and both click events working fine but I cannot get the feature on which click event performed. This is the code
handler = new OpenLayers.Handler.Click(
select,
{
click: function(evt)
{
var feature = this.layer.getFeatureFromEvent(evt);
console.log(feature); // output null
if(this.layer.selectedFeatures){
this.unselect(this.layer.selectedFeatures[0]);
}
},
dblclick: function(evt)
{
// some other operation
}
},
{
single: true,
double: true,
stopDouble: true,
stopSingle: true
}
);
handler.activate();
Any idea which thing is missing in this code?
Thank you
For The Above Question this might solve your answer with few changes
var handler = new OpenLayers.Handler.Click(
layerName, {
click: function(evt) {
console.log('click has triggered');
var feature = layerName.getFeatureFromEvent(evt);
}
,dblclick: function(evt) {
console.log('dblclick has triggered');
}
},{
single: true
,double: true
,stopSingle: true
,stopDouble: true
}
);
handler.activate();
I have been in a similar situation and used the getClosestFeatureToCoordinate method of the layer source. The code would be something like:
click: function(evt) {
var coord = evt.coordinate;
var source = this.layer.getSource();
var feature = source.getClosestFeatureToCoordinate(coord);
// do something with feature
}
I have done in this way.
click: function(evt) {
var pos = map.getLonLatFromPixel(xy);
var point = new OpenLayers.Geometry.Point(pos.lon, pos.lat);
var list = $.map(this.layer.features, function(v) {
return v.geometry.distanceTo(point);
}); // get distance of all features
var min = (Math.min.apply(null, list)); // minimum distance
var closest = $.map(this.layer.features, function(v) {
if (v.geometry.distanceTo(point) == min)
return v;
});
feature = closest[0];
}

Extjs reset filefield input

How reset filefield input in ExtJS? I am trying:
//this - point on Ext.panel.Form
var form = this.getForm();
form.reset();
var filefield = this.getForm().getFields().get(0);
filefield.reset();
filefield.setValue('');
filefield.value = '';
But not one of these methods don't work. Thank you for help!
Use below code will help you
function clearFileUpload(id){
// get the file upload element
fileField = document.getElementById(id);
// get the file upload parent element
parentNod = fileField.parentNode;
// create new element
tmpForm = document.createElement("form");
parentNod.replaceChild(tmpForm,fileField);
tmpForm.appendChild(fileField);
tmpForm.reset();
parentNod.replaceChild(fileField,tmpForm);
}
Old post, but I encountered this problem as well, and I found a cleaner solution.
First of all make sure , the filefield has allowBlank: true set.
Then you can call the setRawValue method as so :
filefield.setRawValue("");
The easiest way that you might be looking for would be :
filefield.fileInputEl.dom.value = '';
Based on this answer: HTML input file selection event not firing upon selecting the same file
In Ext.ux.form.FileUploadField component add the following code in the change event under the bindListeners function.
var that = this;
setTimeout(function() {
that.fileInput.dom.value = null;
that.setValue(that.fileInput.dom.value);
}, 100);
bindListeners: function(){
this.fileInput.on({
scope: this,
mouseenter: function() {
this.button.addClass(['x-btn-over','x-btn-focus'])
},
mouseleave: function(){
this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
},
mousedown: function(){
this.button.addClass('x-btn-click')
},
mouseup: function(){
this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
},
change: function(){
var v = this.fileInput.dom.value;
this.setValue(v);
this.fireEvent('fileselected', this, v);
var that = this;
setTimeout(function() {
that.fileInput.dom.value = null;
that.setValue(that.fileInput.dom.value);
}, 100);
}
});
},

Categories

Resources