I'm trying to create a jQuery control using the widget factory. The idea is that I turn a button into a jQuery button, give it an icon, and register the click event for that button such that when invoked, it displays a calendar control on a textbox, whose id is passed in as an option to the widget method:
$.widget("calendarButton", {
options: {
textFieldId: ''
},
_create: function () {
this.element.button(
{
icons: {
primary: "ui-icon-calendar"
}
}).click(function () {
if (this.options.textFieldId != '') {
$(this.options.textFieldId).datetimepicker('show');
return false;
}
});
}
});
The problem with this however, is that this.options is undefined when the click handler is invoked; which makes sense since the method has a different scope. So I tried to see if there is a way to define a "static" variable which then can be accessed inside the callback method. I found this answer that explained how to create variables inside a wrapper function like this:
(function ($) {
var $options = this.options;
$.widget("calendarButton", {
options: {
textFieldId: ''
},
_create: function () {
this.element.button(
{
icons: {
primary: "ui-icon-calendar"
}
}).click(function () {
if ($options.textFieldId != '') {
$($options.textFieldId).datetimepicker('show');
return false;
}
});
}
});
})(jQuery);
But it still reports that $options is undefined. Is there a way to achieve this? I'm trying to avoid requiring the callback function be passed in since it'll be pretty much the same for all instances. Any help is appreciated.
After playing with it for a few hours, I finally came across the jQuery Proxy method which is exactly what I was looking for. I changed the code a little bit to look like this:
$.widget("calendarButton", {
options: {
textFieldId: ''
},
_create: function () {
this.element.button(
{
icons: {
primary: "ui-icon-calendar"
}
}).on("click", $.proxy(this._clickHandler, this));
},
_clickHandler: function () {
if (this.options.textFieldId != '') {
$(this.options.textFieldId).datetimepicker('show');
}
}
});
Notice that instead of implementing the click callback directly, I'm essentially creating a delegate that points to my private _clickHandler function, which itself runs on the same context as the $.widget() method (since the second argument of $.proxy(this._clickHandler, this) returns $.widget()'s context) hence availablity of the options variable inside the method.
Related
i'm trying to implement a text selection listener to display a toolbar for some custom options
<script>
export default {
name: "home",
created() {
document.onselectionchange = function() {
this.showMenu();
};
},
data() {
return {
...
};
},
methods: {
showMenu() {
console.log("show menu");
}
}
</script>
<style scoped>
</style>
but it still display that can't call showMenu of undefined, so i tried in this way:
created() {
vm = this;
document.onselectionchange = function() {
vm.showMenu();
};
},
so, nothing changed =(
i need to use this selectionchange because its the only listener that i can add that will handle desktop and mobile together, other method i should implement a touchup, touchdown and its not working for devices
Functions declared the classic way do have their own this. You can fix that by either explicitly binding this using Function.prototype.bind() or by using an ES6 arrow function (which does not have an own this, preserving the outer one).
The second problem is that if you have more than one of those components you've shown, each will re-assign (and thus, overwrite) the listener if you attach it using the assignment document.onselectionchange =. This would result in only the last select element working as you expect because it's the last one assigned.
To fix that, I suggest you use addEventListener() instead:
document.addEventListener('selectionchange', function() {
this.showMenu();
}.bind(this));
or
document.addEventListener('selectionchange', () => {
this.showMenu();
});
A third solution stores a reference to this and uses that in a closure:
const self = this;
document.addEventListener('selectionchange', function() {
self.showMenu();
});
With x-tag I am trying to find a way to extend every html element that I put is:"ajax-pop" attribute.
What I want to do is when I click an element with is:"ajax-pop" attribute I will do some dynamic ajax loads. It will be a good starting point for me to develop a manageble system.
I know I can do it with some different ways but I am wondering is there a way to do it like this way extends:'every single native html element'
xtag.register('ajax-pop', {
extends: 'WHAT SHOULD I WRITE HERE???',
lifecycle: {
created: function () {
},
inserted: function () {
},
removed: function () { },
attributeChanged: function () { }
},
methods: {
someMethod: function () { }
},
accessors: {
popUrp: {
attribute: {
name: "pop-url"
}
},
},
events: {
tap: function () { },
focus: function () { }
}
});
Type extensions must be defined element by element. A single custom element cannot extend multiple standard elements.
For, each custom element owns it own prototype, that can't be reused.
If you want to extend a button (for example), you have to write in JavaScript :
xtag.register('ajax-pop', {
extends: 'button',
...
And, in the HTML page:
<button is="ajax-pop">
...
You can do this using x-tag's delegate pseudo, and by adding a data- attribute to elements you wish to have this behavior:
<article data-pop="/path/to/content.html"></article>
And your JavaScript would be something like this:
xtag.addEvent(document.body, 'tap:delegate([data-pop])', function (e) {
var uri = this.getAttribute('data-pop');
$.get(uri).done(function (res) {
this.innerHTML = res;
}.bind(this));
});
Here's a codepen example:
http://codepen.io/jpecor-pmi/pen/Vexqyg
I believe you're going about using x-tag the wrong way. X-tag is meant to be used to implement entirely new tags; what you're trying to do is simply modify different pre-existing DOM elements. This can easily be done in pure javascript or more easily in jquery by assigning each desired element a shared class.
Skip to bottom for question
JQuery plugin:
$.fn.myPlugin = function( options ) {
var options = $.extend({
myOption: true,
edit: function() {},
done: function() {}
}, options);
options.edit.call(this);
options.done.call(this);
//plugin guts removed to prevent over complication
return {
edit: function(obj) {
$(obj).closest('#myParent').find('#myInput').autosizeInput(); //plugin to autosize an input
},
done: function(obj) {
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
}
}
});
Bear in mind this is a cut down version of my plugin.
Called from page:
$(document).ready(function() {
var myPlugin = $('.editable').myPlugin({
edit: $(this).on('click', '.edit-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.edit( $(this) ); //call the edit returned function
}),
done: $(this).on('click', '.done-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.done( $(this) ); //call the done returned function
});
});
});
This works great for the most part, however, what i really want is have functions called from inside my plugin every time a specific callback is triggered - without the need to call from outside the plugin.
I have tried including delegated events in my plugin:
$(this).on('click', '.edit-td', function(e) {
e.preventDefault();
$(this).closest('#myParent').find('#myInput').autosizeInput();
});
$(this).on('click', '.done-td', function(e) {
e.preventDefault();
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
});
But when the .edit-td is triggered it propagates and triggers the .done-td event, if i put e.stopPropagation() in the edit-td function (because it has been delegated) edit-td stops firing completely.
And non-delegated method:
$(this).find('.done-td').click(function(e, this) {});
But I can't parse the returned object (this) to the internal function before the internal function has completed. (just comes up undefined or missing formal parameter).
*Skip to here
To avoid the question becoming to localised -
I need to have functions called from inside my
plugin every time a specific callback is triggered.
Without calling it using closures
Something like:
if( $.fn.myPlugin.callback().is('edit') ) {
//fire function
}
I needed to return a function(s) like so:
return {
enable: function(arg) {
//do something
},
disable: function(arg) {
//do something
}
}
That way I can call it from inside my plugin by referencing itself like this:
this.myPlugin().disable();
I'm trying to bind a click event to the function below, however the entire function is currently being run when being binded in the document ready.
Is it possible to run it solely on the click event? Possibly it has something to do with the way my method is composed?
Thanks in advance
$(function() {
$("#expand-search").on("click", search.resize());
});
var search = {
element: $('#search_advanced'),
resize: function() {
search.element.slideToggle(400, 'swing', search.buttonState());
},
buttonState: function() {
if(search.element.is(':hidden')) {
console.log('hidden');
} else {
console.log('visible');
}
}
};
You are calling the function (handler) instead of passing the reference (name) of function (handler) to on().
Change
$("#expand-search").on("click", search.resize());
To
$("#expand-search").on("click", search.resize);
No parenthesis to event handlers! You want to pass the function-to-be-executed, not the result from executing it. Also, you will need to move your search object inside the ready handler since you use selectors for its initialisation.
$(function() {
var search = {
element: $('#search_advanced'),
resize: function() {
search.element.slideToggle(400, 'swing', search.buttonState);
},
buttonState: function() {
if(search.element.is(':hidden')) {
console.log('hidden');
} else {
console.log('visible');
}
}
};
$("#expand-search").on("click", search.resize);
});
I have added a custom edit button control on the jqGrid navigator as follows:
jQuery("#grid").navButtonAdd('#pager',
{
caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editSelectedRow,
position: "last",
title:"click to edit selected row",
cursor: "pointer",
id: "edit-row"
}
);
So that rather than use the default function: editGridRow, it uses my custom function editSelectedRow. However, I also want to add the doubleClick function to so that it calls editSelectedRow on doubleClick.
using the default editGridRow function works as such
ondblClickRow: function()
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
jQuery(this).jqGrid('editGridRow', rowid);
}
However, when I replace the default editGridRow function with my default function editSelectedRow as such,
ondblClickRow: function()
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
jQuery(this).jqGrid('editSelectedRow', rowid);
}
I get the following error within firebug:
uncaught exception: jqGrid - No such method: editSelectedRow
The function editSelectedRow however does exist and works with clicking the custom edit button. Please help, thanks.
UPDATE:
#Oleg: As requested here's the code defining method: editSelectedRow
function editSelectedRow(rowid)
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
if( rowid != null )
{
var dialogId = '#edit-form-dialog';
var dialogTitle = 'Edit Customer';
$(dialogId).load('/customer/edit/id/' + rowid, function ()
{
$(this).dialog(
{
modal: false,
resizable: true,
minWidth: 650,
minHeight: 300,
height: $(window).height() * 0.95,
title: dialogTitle,
buttons:
{
"Save": function ()
{
var form = $('form', this);
$(form).submit();
$("#grid").trigger("reloadGrid");
},
"Cancel": function ()
{
$("#grid").trigger("reloadGrid");
$(this).dialog('close');
}
}
});
LaunchEditForm(this);
});
}
else
{
jQuery( "#dialogSelectRow" ).dialog();
}
return false;
}
#Oleg: Thanks, you advised against using a custom method editSelectedRow in place of method editGridRow. The reason I am using this is that my forms are Zend Forms and I need all the bells and whistles of Zend Form to be available. The server generates this form and it's loaded into a dialog form. If there's a way to still achieve this without resorting to my editSelectedRow custom method, I'd be glad to learn it. Thanks.
You question is pure JavaScript question.
If you define the function editSelectedRow as
function editSelectedRow(rowid)
{
...
}
you can call it as editSelectedRow(rowid) and not as jQuery(this).jqGrid('editSelectedRow', rowid);.
Another problem is that you use this inside of he body of editSelectedRow function. It's not correct. You can define editSelectedRow function in a little another way
var editSelectedRow = function (rowid) {
...
};
In the case editSelectedRow will be able to bind this to any value. To do this you need use another form of invocation of the function. Inside of ondblClickRow it will be
ondblClickRow: function () {
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
editSelectedRow.call(this, rowid);
}
In the above example the first parameter of call is the value used as this inside of the function. We forward just the current this value forward to editSelectedRow. If we would use the form editSelectedRow(rowid); for the invocation of the function the value of this inside of function will be initialized to window object.
The usage of editSelectedRow inside of navButtonAdd can stay unchanged.