I have a Google Apps Script that dynamically generates buttons and assigns for each a ClickHandler which in turn calls a function.
My problem is that because every button calls the same function I can't find a way to indentify which of them actually made the call. Here is a code sample:
var handler = app.createServerHandler("buttonAction");
for (i=1,...) {
app.createButton(...).setId(i).addClickHandler(handler);
}
function buttonAction() {
//How do I know what button made the call?
}
Another option is to use the e.parameter.source value to determine the ID of the element that triggered the serverHandler to be called.
Here's an example:
function doGet(e) {
var app = UiApp.createApplication();
var handler = app.createServerHandler("buttonAction");
for (var i = 0; i < 4; i++) {
app.add(app.createButton('button'+i).setId(i).addClickHandler(handler));
}
return app;
}
function buttonAction(e) {
var app = UiApp.getActiveApplication();
Logger.log(e.parameter.source);
}
e.parameter.source will contain the ID of the element, which you could then use to call app.getElementById(e.parameter.source) ...
You could create multiple handlers, each for one button:
for (i=1,...) {
var handler = app.createServerHandler("buttonAction" + i);
app.createButton(...).setId(i).addClickHandler(handler);
}
function buttonAction1() {
// code to handle button 1
}
function buttonAction2() {
// code to handle button 2
}
function buttonAction...
I wouldn't recommend of having these sort of "anonymous" action handlers though, as you might be having troubles later in remembering which actionX does what.
(e.g. have a different approach, w/o a loop, or prepare a dictionary-like/array object of meaningful handler names before that loop.)
OTOH, you could use event object argument provided to your callback function:
function buttonAction(event) {
// use event object here to identify where this event came from
}
The thing is the above event object properties depends on where your callback is being called from. For instance, if it were a submit button where you had a Form, then you could access parameters submitted by that from like so: event.parameter.myParamName. See code sample here.
So, if you have a variable number of buttons, you could use a hidden element + the button:
for (i=1,...) {
var hiddenAction = app.createHidden("action", "action"+i);
var handler = app.createServerHandler("buttonAction");
handler.addCallbackElement(hiddenAction);
var btn = app.createButton("Button text", handler);
// you'll need to add both btn and hidden field
// to the UI
app.add(hiddenAction);
app.add(btn);
}
Then, your buttonAction might look like this:
function buttonAction(e) {
var action = e.parameter.action;
// do something based on action value here
// which will be one of "action1", "action2", ...
}
The above is a copy & paste from Hidden class sample.
The above might not work out of the box, but you get the idea: create a hidden element that holds the info you need in your callback, and attach that hidden to your server handler. You could even create multiple hidden elements or a Form panel.
I have the same issue. It works using Tag.
EG
SETUP
var button = addButton(app
,panel
,"buttonActiveTrelloProjects_" + i.toString()
,appVars.buttonWidth() + "px"
,appVars.level2ButtonHeight().toString() + "px"
,false
,false
,"Trello"
,"buttonActiveTrelloProjectsHandler"
,(appVars.buttonLhsGap() * buttonCntr) + (appVars.buttonWidth() * (buttonCntr - 1 ) + 9)
,(appVars.level2ButtonTopGap() * 34)
,3
,"button");
button.setTag(projectName );
USE
function buttonActiveProjectsChartHandler_1(button){
...
buttonTag = getButtonTag(button);
chartType = buttonTag.split(";")[1];
activeProject = buttonTag.split(";")[0];
...
}
function getButtonTag(button){
var jsonButton = JSON.stringify(button);
var source = button.parameter.source;
var tagPtr = source + "_tag";
return button.parameter[tagPtr];
}
Related
Structure Concept:-
Basically, i am trying to create the modal window containing input and that modal window currently fires when the input on index page get focused for that I have used data attribute to make a link between them by assigning them same attribute value.
Javascript Concept:-
for the modal window, I have created the modal object. and model object contains a bindModal method which takes one argument and that argument is data attribute value. after taking that value bindModal method will search dom elements containing that particular value and after the search, I iterate over them using each loop.
Problem
So basically I want whenever user starts typing on the model input it should get written automatically in input on the index page.
I will appreciate you all if guys help me out to make my code more optimized and well structured and most important thing is that let me know what mistake I have done in overall work Thanks
JavaScript Code
var modal = function () {
this.toggleModal = function () {
$('#modal').toggleClass('content--inActive').promise().done(function () {
$('#modal__close').on('click',function(){
$('#modal').addClass('content--inActive');
});
});
}
this.bindModal = function (bindVal) {
var bindValue = $(document).find('[data-modal-bind = ' + bindVal + ']');
$.each(bindValue, function (index) {
var bind1 = $(this);
if(index === 1) {
var bind2 = $(this);
$(bind1).change(function (){
$(bind2).val(bind1.val());
});
}
});
}
}
var open = new modal();
$('#input_search').on('click',function(){
open.toggleModal();
open.bindModal('input');
});
Here is one way to do what you want:
var modal = function() {
this.bindModal = function(bindVal) {
var bindValue = $('[data-modal-bind = ' + bindVal + ']');
bindValue.each(function(index) {
$(this).keyup(function() {
var value = $(this).val();
bindValue.each(function(i, e) {
$(this).val(value);
});
});
});
}
}
$('#input_search').on('click', function() {
var open = new modal();
open.bindModal('input');
});
Changes done:
I cached the inputs with same binding values in bindValue variable, and then bound the the keyup event for each of them. On keyup, the value of the current input is get in value, which is then assigned to each input using the inner loop.
This makes the inputs to be in sync while typing. Hope that solves your issue.
I'm trying to get rid of the inline javascript that mojarra creates to use the header x-content-security-policy. It's a header that disable inline script.
In order to do so I add a class to a button called jsfajax and I basically add an onclickevent listener to element which wear that class. I then call in mojarra.ab in that event listener. However the source parameter is null and I think that is why I can't get to the method in my bean.
HTTP request FORM DATA :
j_idt240:j_idt240
javax.faces.ViewState:-xxxxxxxxxxxxxx3:xxxxxxxxxxxx7022321
javax.faces.source:
javax.faces.partial.event:click
javax.faces.partial.execute:j_idt240:j_idt241
javax.faces.behavior.event:action
javax.faces.partial.ajax:true
<h:commandButton styleClass="jsfajax" value="go" action="#{test.sayHi}">
JS:
var es = doc.getElementsByClassName('jsfajax');
for(var i = 0; i < es.length; i++){
myjsf(i, es);
}
});
function myjsf(i , es){
var e = es[i];
e.onclick = function(evt){
log(this); // outputs the button so I don't understand + jsf.ajax.request doesn't throw error
mojarra.ab(this,evt,'action',0,0);
return false;
}
}
So the request is sent but it never reaches the action method.
However this does (and the source is the btn):
<h:commandButton value="go2" action="#{test.sayHi}">
<f:ajax/>
</h:commandButton>
At the end of request() there is :
var sendRequest = function() {
var ajaxEngine = new AjaxEngine(context);
ajaxEngine.setupArguments(args);
ajaxEngine.queryString = viewState;
ajaxEngine.context.onevent = onevent;
ajaxEngine.context.onerror = onerror;
ajaxEngine.context.sourceid = element.id;
ajaxEngine.context.render = args[namingContainerId + "javax.faces.partial.render"];
ajaxEngine.sendRequest();
It was because when adding the <f:ajax> tag the container adds an ID to the element - which kinda makes sens when it's a direct form submit the id is not needed when there is no f:ajax, thus not going through request()- . Which wasn't found in jsf.ajax.request.
So I just did this :
e.onclick = function(evt, e){
this.id = this.name;
mojarra.ab(this,evt,'action',0,0);
return false;
}
I'm not sure if that can cause any issue though. Else I'll just put id in my button.
Here is the block of code I want to replace:
$(document).ready(function () {
$(".button-purple").click(function () {
interval = $(this).attr('id');
name = $(this.attr('name');
if(Number($(this).val()) === 0) {
if(name == 'static') {
do this
}
else {
do this
}
}
else {
do this
}
});
});
I can't find any documentation on trying to replace the function since it's unnamed though. Is it possible to replace the entire javascript file + delete the line loading it / insert my own script? Would really appreciate any help I can get.
If you just want to remove the click event handler, then simply say
var $element = $(".button-purple");
$element.off('click');
If you want to Remove all the event handlers, then you'll first have to find out what all event handlers are present and then remove them iteratively.
var element = $element[0]; //Make sure the element is a DOM object and not jQuery Object.
// Use this line if you're using jQuery 1.8+
var attachedEvents = $._data(element,'events');
// Use this line if you're using jQuery < 1.8
var attachedEvents = $(element).data('events'); //Here you can also replace $(element) with $element as declared above.
for(var event in attachedEvents){
$element.off(event);
}
UPDATE:
You can simply add your own event handler (using .on() API) after you're done removing all the required existing handlers.
Just define your function.
function yourFunction(){ /* your code */};
$element.on('click', yourFunction);
Update 2:
Since you just want to remove the click event handler, this is the simplest code that will serve your purpose.
$(".button-purple").off('click').on('click', yourFunction);
I'm not aware of tampermonkey, but you can try this:
function chickHandler() {
interval = $(this).attr('id');
name = $(this.attr('name');
if (Number($(this).val()) === 0) {
if (name == 'static') {
do this
} else {
do this
}
} else {
do this
}
}
}
function onReadyHandler() {
$(".button-purple").click(chickHandler);
}
$(document).ready(onReadyHandler);
When you do something like .click(function(){...}), here function is called as a callback. You have to send a function as a callback. Not necessary to be anonymous.
I understand that onclick() in html with parenthesis calls automatically. But in my situation, I want to pass a parameter into the onclick function(specifically, the element clicked). So how do I manage this without having onclick fired when the page loads? In addition, the onclick method does not fire after its automatically firing upon loading. My code is below:
for (i = 0; i < returnPostPhotoSrcs().length; i++) {
// var photosArray=returnPhotoNames()
// var imgName=photosArray[i]
var imgSrcArray=returnPostPhotoSrcs();
var imgSrc=imgSrcArray[i]
var postNamesArray=returnPostNamesArray();
var postName=returnPostNamesArray[i]
var img=img_create(imgSrc,postName,'')
img.style.width=returnPostHeight();
img.style.height=returnPostWidth();
img.className="postImage";
img.onmousedown=playShout(img);
var postNamesArray=returnPostNames();
var innerSpan = document.createElement('span');
innerSpan.onmousedown=playShout(innerSpan); //problem line
var text = postNamesArray[i];
innerSpan.innerHTML = text; // clear existing, dont actually know what this does
var outerSpan = document.createElement('span');
outerSpan.className="text-content";
outerSpan.onmousedown=playShout(outerSpan); //another problem line, also doesnt call onclick
var li = document.createElement('li');
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(img)
outerSpan.appendChild(innerSpan)
li.appendChild(imgSpacer)
imgSpacer.style.opacity="0"
// if (i>0 && i<returnPostPhotoSrcs().length-1) {
// hackey
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(imgSpacer)
li.appendChild(outerSpan)
imgSpacer.style.opacity="0"
// }
var outerDiv = document.getElementById("postDivOuter");
outerDiv.appendChild(li)
}
Adding onto this you could also do:
img.onmousedown= function(e) { playShout(e) };
//for playshout
playshout = function(e) {
var element = e.target; //this contains the element that was clicked
};
The function fires because you are calling it. You need to use a closure
img.onmousedown= function() { playShout(img) };
As others have shown, you can create an anonymous function, or another option is to use .bind():
innerSpan.onmousedown = playShout.bind(null, innerSpan);
I have a button in my project that when you click over it a function call and add onclick event to all certain elements in my project and show my hidden popup element container.
I have a function that search all exist element in my page and add onclick event to some of elements that they have certain class.
My element is stored in a list array. in each cell of this array (array name is list) stored an element like below:
list[0] = document.getElementById("my_div_id");
list[1] = document.getElementById("my_div_id_1");
list[2] = document.getElementById("my_div_id_2");
...
list[n] = document.getElementById("my_div_id_n");
and I have a function like below in top of my Javascript code:
function say_hello(e, msg) {
if (e == null) e = window.event;
//now e handler mouse event in all browser !!!
alert (e + "::" + msg);
}
I have a function to add onclick event to each element in array. I add onclick event in type of below (separated with (*) comment) but doesn't work any of them:
function search_and_add_events_to_all_dragable_elements (list) {
for (var z = 0; z < list.length; z++) {
list[z].href = "javascript:;";
var e;
var test_msg = "VAYYYYYYYYYY";
/**************
element.onclick = new Function { alert ('hi'); };
element.onclick = new Function () { alert ('hi'); };
element.onclick = new function { alert ('hi'); };
element.onclick = new function () { alert ('hi'); };
element.onclick = new function () { return alert ('hi'); };
element.onclick = function () { return alert ('hi'); };
element.onclick = alert ('hi');
element.onclick = "alert ('hi');";
element.onclick = say_hello(e, test_msg);
element.onclick = "say_hello();";
element.onclick = (function (e, test_msg) { return function(e) { sib(e, test_msg); };
element.onclick = (function () { return function() { alert("ahaaay"); };
**************/
list[z].style["padding"] = "20px";
list[z].style["border"] = "solid 10px";
list[z].style["backgroundColor"] = "#CCC";
}
}
I change style in end of my code to perform my code is work and end truly. style change every time but onclick event doesn't add to my div.
only one way add onclick to my project. that is same as below:
list[z].setAttribute("onclick", "alert(\"hi\");");
but are there better ways?
There is a better way. My first mistake was using JavaScript before my all element load on my page. to solve it you must call element in end of page load or put your javascript code in end of your project. then your code execute exactly when your elements are exist in your page.
for more details about it see links below:
JavaScript that executes after page load
http://www.w3schools.com/jsref/event_onload.asp
My second mistake was hurt :(
I has a div that hold all of my other elements in itself. it was styled display: none; on load. when I call my function it was displayed none and all thins work well (like my new styling) but onclick event didn't work :(( and I spent two days to solve this :((
only be careful your element should not be display: none styled when you are adding your onclick event to it.
then you can use this type of creation onclick event dynamically to your project:
list[z].onclick = (function (e, test_msg) {
return function(e) {
sib(e, test_msg);
};
})(e, test_msg);
this is best way that I know. you can manage event handler and send your arguments also to your function.
I use several time another way of dynamically add onclick event in my project.