How to access caller element inside callback function - javascript

I have a jquery-ui button test-button that has a data attribute.
That button calls a custom widget customWidget that has a callback function fnSaveCallback.
$(".test-button").button({
icons: {
primary: 'icon-test icon-mixed icon-custom'
},
text: false
}).customWidget({
id: "custom-widget",
title: "My custom widget",
fnSaveCallback: function() {
// Need to get the data-test attribute from the "test-button"
}
});
I'm having problems trying to access the the test-button in order to get the value of the data-attribute from the callback function.
Any idea how can i do that? Thanks in advance!

I've found an easy way to handle this adding a class on the click event.
$(".test-button").button({
icons: {
primary: 'icon-test icon-mixed icon-custom'
},
text: false
}).click(function() {
// remove opener class from other test-buttons
$(.test-button.opener).removeClass("opener");
// add opener class to the clicked button
$(this).addClass("opener");
}.customWidget({
id: "custom-widget",
title: "My custom widget",
fnSaveCallback: function() {
// Get the data-test attribute from the "test-button"
$(".test-button.opener").data("test");
}
});

You need to have a reference of the element somewhere.
const test_button = document.getElementById('test-button');
and then in fvSaveCallback:
fnSaveCallback: function() {
// Need to get the data-test attribute from the "test-button"
console.log(test_button.dataset.test);
}
EDIT: After your edit, as far as I understand you are trying to apply that method to all .test-button buttons.
You should only need to get a list of nodes, and iterate through it :)
const test_buttons = document.getElementsByClassName('test-button')
;
for (let i = 0; i < test_buttons.length; i++)
{ const button = test_buttons[i]; //This is the button
// Do with 'button' whatever you want here.
console.log(button.dataset.some_data);
}

Related

jQuery .remove() does not work with div created inside the function

I've tried a couple of things since yesterday, but I can't achieve my goal.
The idea is :
When clicking on a character "Div", it appears a little menu to change a parameter inside my website. The problem is, I want to remove the "Class Picker", but it just does not work.
var CharacterClasses = [
{ id: 1, name: 'Warrior', cssClass: 'warrior'},
{ id: 2, name: 'Paladin', cssClass: 'paladin'},
...
]
$('.group_miniature').click( function(){
// Removing all existant class choices
$(".group-panel_class_picker").remove()
// Creating the class picker
var Panel = $("<div id=\"panel_class_picker\"></div>").addClass('group-panel_class_picker')
// Append the whole thing
$(this).append(Panel)
// Iterating each class to add a div
CharacterClasses.forEach( function(item){
// Creating the div
let btn_class = $("<div>&nbsp</div>").addClass( [item.cssClass,'group-btn_class'] )
Panel.append(btn_class)
Panel.on("click", ".group-btn_class", function(event){
$(this).parent().remove() // This is my problem, it does not remove the parent
console.log('Click :)') // This appears in my console
})
})
})
Panel.on("click", ".group-btn_class", function(event){
$(this).parent().hide()
event.stopPropagation()
console.log('Click criss')
})
I discovered that I had to add event.stopPropagation()
Now it works just fine ! :)

Javascript variable scope when adding function to array

I am using TinyMCE 4 and trying to build a dynamic menu. In order to do this I am building an array of menu items which includes an onclick function. The menu displays, but the onclick function does not work because when building the array, the value I need to pass to the function is out of scope - I believe.
var MenuItems = [{"Id":"1","Name":"MenuItem 1"},{"Id":"2","Name":"MenuItem 2"}];
var Menu = [];
for (var i=0;i<MenuItems.length;i++)
{
Menu.push({
text: MenuItems[i].Name,
onclick: function(){
alert(MenuItems[i].Id);
}
});
}
In the onclick declaration, MenuItems[i].Id is not in scope - I believe.
How can I pass the values to the onclick function.
I am then passing the array to the TinyMCE plugin, but I don't believe this is a problem with TinyMCE, but posting this part in case there is a better way.
tinymce.PluginManager.add('myplugin', function(editor, url) {
editor.addButton('menu', {
text: 'MyMenu',
type: 'menubutton',
icon: false,
menu: Menu
});
});
MenuItems[] won't be available when the callback for myplugin would run.
This would also mean, that once, onclick of any menuItem is called, it would try accessing MenuItems[].
To fix this, once way could be to change the implementation like:
var MenuItems = [{"Id":"1","Name":"MenuItem 1"},{"Id":"2","Name":"MenuItem 2"}];
var Menu = [];
for (var i=0;i<MenuItems.length;i++)
{
const id = MenuItems[i].Id;
Menu.push({
text: MenuItems[i].Name,
onclick: function(){
alert(id);
}
});
}

how to execute local method from Ext.Template and Ext.apply methods

I want to execute a local method in Ext.Template context.
The method should be a member in the class.
I tried the following code and it doesn't work.
Someone know of can I pass the function member to onClick event?
requires: ['Ext.XTemplate'],
alias : 'widget.countlinkcolumn',
func: 'this.handleFilter'
renderer: function(val,metaData,rec,b,c,d,f){
var categoryId = 3;
var colTemplate = new Ext.Template(
'<div class="drill_down_link grid_cell_link" style="cursor: pointer; float:right" onclick="{on_click}({categoryId})">{text}</div>' +
'</div>');
var tpl = colTemplate.apply({
text: text,
categoryId: categoryId,
on_click: this.func,
});
return tpl;
},
handleFilter: function (categoryId) {
console.log(categoryId);
},
});
Never found an simple solution to this problem... The XTemplate can't directly call ExtJS code from it (it's actually already rendered in the DOM)...
The workaround we found is to render the XTemplate in a View (But you can do it with apply()) then listening to the itemClick event.
In the listener we get the DOM element and we can get some additional data from an attribute (eg: data-categoryId):
xtype: 'view',
listeners: {
itemClick: 'onItemClick',
}
// Additional attribute (data-categoryId) that store the categoryId
tpl: '<div data-categoryId="{categoryId}" class="drill_down_link">{text}</div>'
Then in the listener we can use this additional attribute after we checked that the correct button was clicked (by his class name but you can use other attribute)
onItemClick: function(dataView, record, item, index, e, removeAll){
var me = this,
target = e && e.target,
targetClass = target && target.getAttribute("class");
//Clicked on link (identified by his class name)
var isLink = targetClass && targetClass.indexOf("drill_down_link") >= 0;
if(isLink){
// Get the attribute value we setted in the XTemplate
var categoryId = target.getAttribute('data-categoryId');
}
}

Ionic: How is it possible to change $ionicPopup subTitle's text programmatically?

I'm trying to change the value as well as the style of the subText attribute associated with an $ionicPopup somewhere in my app.
I searched everywhere, but didn't find yet any method for doing so.
So how is that possible?
Thanks.
If you want to change popup after it been shown,
you can use selectors and angular jqlite wrapper.
Code is like this
onTap: function(e) {
var result = document.getElementsByClassName("popup-sub-title");
angular.element(result).html('dsaadsds')
e.preventDefault();
}
You have here a working codepen.
You cannot change the subTitle directly using the configuration option, as by defined in the specification it accepts an optional String value
{
title: '', // String. The title of the popup.
cssClass: '', // String, The custom CSS class name
subTitle: '', // String (optional). The sub-title of the popup.
}
UPDATE:
You can assign a value to a $scope property within onTap to assign a success message
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function(e) {
$scope.success = {
message: 'Hello World!'
};
e.preventDefault();
}
}
And now you can access $scope.success.message to show the success message

Redefining a jQuery dialog button

In our application we use a general function to create jQuery dialogs which contain module-specific content. The custom dialog consists of 3 buttons (Cancel, Save, Apply). Apply does the same as Save but also closes the dialog.
Many modules are still using a custom post instead of an ajax-post. For this reason I'm looking to overwrite/redefine the buttons which are on a specific dialog.
So far I've got the buttons, but I'm unable to do something with them. Is it possible to get the buttons from a dialog (yes, I know) but apply a different function to them?
My code so far:
function OverrideDialogButtonCallbacks(sDialogInstance) {
oButtons = $( '#dialog' ).dialog( 'option', 'buttons' );
console.log(oButtons); // logs the buttons correctly
if(sDialogInstance == 'TestInstance') {
oButtons.Save = function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
}
}
}
$('#dialog').dialog({
'buttons' : {
'Save' : {
id:"btn-save", // provide the id, if you want to apply a callback based on id selector
click: function() {
//
},
},
}
});
Did you try this? to override button's callback based on the need.
No need to re-assign at all. Try this.
function OverrideDialogButtonCallbacks(dialogSelector) {
var button = $(dialogSelector + " ~ .ui-dialog-buttonpane")
.find("button:contains('Save')");
button.unbind("click").on("click", function() {
alert("save overriden!");
});
}
Call it like OverrideDialogButtonCallbacks("#dialog");
Working fiddle: http://jsfiddle.net/codovations/yzfVT/
You can get the buttons using $(..).dialog('option', 'buttons'). This returns an array of objects that you can then rewire by searching through them and adjusting the click event:
// Rewire the callback for the first button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons[0].click = function() { alert('Click rewired!'); };
See this fiddle for an example: http://jsfiddle.net/z4TTH/2/
If necessary, you can check the text of the button using button[i].text.
UPDATE:
The buttons option can be one of two forms, one is an array as described above, the other is an object where each property is the name of the button. To rewire the click event in this instance it's necessary to update the buttons option in the dialog:
// Rewire the callback for the OK button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons.Ok = function() { alert('Click rewired!'); };
$('#dialog').dialog('option', 'buttons', buttons);
See this fiddle: http://jsfiddle.net/z4TTH/3/
Can you try binding your new function code with Click event of Save?
if(sDialogInstance == 'TestInstance') {
$('#'+savebtn_id).click(function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
});
}

Categories