How to create shortcut keys in extjs - javascript

I write this code for submit on Enter
{
fieldLabel : 'Password',
name : 'j_password',
inputType : 'password',
allowBlank : false,
listeners : {
'render' : function(cmp) {
cmp.getEl().on('keypress', function(e) {
if (e.getKey() == e.ENTER) {
submitform();
}
});
}
}
}
What change do I need to do for shortcut keys Like Save(Ctrl + S),Paste(Ctrl +P), Open (Ctrl + O), Exit(Ctrl +X)?

You need to write appropriate handler to do the job using KeyMap.
Ext 4 code snippet may be as follows -
Ext.onReady(function () {
var map = new Ext.util.KeyMap(document,{
key: [VALUES-ASCII], // this works,
fn: function(){ alert('key was pressed.!'); }
}
);
});
This may Help

I think, You will solve your problem by this code
I Give many ways.
You choose suitable one from binding:[{}]
scope : this,
listeners : {
afterrender: function(window, options) {
this.keyNav = new Ext.util.KeyMap({
target: window.el,
binding: [{
key: [10,13],
fn: function(){
alert("Return was pressed");
}
}, {
key: "abc",
fn: function(){
alert('a, b or c was pressed');
}
}, {
key: "\t",
ctrl:true,
fn: function(){
submitform();//'Control + tab was pressed
}
}, {
key: "m",
ctrl:true,
fn: function(){
submitform();//'Control + m was pressed
}
}],
scope: this
});
}
}

Related

Is it possible to build a jQuery context menu with link item?

I am wondering, if it is possible to implement in the existing jQuery context menu (link to jQuery custom context menu) a link item, where you can right click on the link to get the default browser context menu.
This is my code so far:
$('.cMenuCust').on('contextmenu', function(e){
$('ul li:nth-child(3)').text((c > 100) ? 'tooMuch' : 'thatsOK');
$('.context-menu-list').width(500);
});
$(function(){
$.contextMenu.types.label = function(item, opt, root) {
$('<span>HTML<span>')
.appendTo(this)
.on('contextmenu', 'a', function(e) {
return true;
});
this.addClass('labels').on('contextmenu:focus', function(e) {
}).on('contextmenu:blur', function(e) {
});
};
$.contextMenu({
selector: '.cMenuCust',
trigger: 'left',
callback: function(key, options) {
if (key === 'a') {
...
} else if (key === 'XLSX') {
...
} else if (key === 'CSV') {
...
}
},
items: {
"title": {name: '{!cmTitel}', disabled: true},
"sep1": "----------------",
"XLS": {name: 'XLS'},
label: {type: "label", customName: "Label", callback: function(){ return false; }, disabled: function(){ return (c > 10000); }},
"CSV": {name: 'CSV'}
}
});
});
Do you have any idea how to get the default browser context menu, if I make a right click on the link item in the jQuery custom context menu (link to jQuery custom context menu)?
Every hint is highly appreciated.
Thanks in advance.

Load extra conditional in backbone js page

I have a backbone app developed externally - initially where I perform the definitions & inject jquery etc..) on the first line - the 7th param is the 'tools template')
I
P.S A lot of code has been removed from here for clarity/ease (as it is well over 800 lines with all the other code) & this is all new to me so feel free to point out any obvious mistakes
On Line 8 - I have the following line:
window.isMobileDevice ? "text!views/tools/templates/i_tools.html" : "text!views/tools/templates/tools.html",
This basically does a 'if a mobile device load mobile page OTHERWISE load the standard (desktop) page.
I want to amend this with some additional logic but unsure how...
I want to add in another conditional, which basically says the following:
if (mobile device)
Load mobile page (as is now) e.g mobile-tools.html
else
if (stampVar == true)
load desktop stamp page e.g stamp-tools.html
else
load the standard desktop page e.g tools.html
Any ideas on how to do this? The stampVar will basically be true/false and i'm trying to work out how to load that in dynamically from an existing js object
define([
"jquery",
"backbone",
"config",
"models/model",
"collections/collection",
"views/tools/toolsBase",
window.isMobileDevice ? "text!views/tools/templates/i_tools.html" : "text!views/tools/templates/stamper_tools.html",
window.isMobileDevice ? "text!views/tools/templates/i_editor.html" : "text!views/tools/templates/editor.html",
window.isMobileDevice ? "text!views/tools/templates/i_txts.html" : "text!views/tools/templates/txts.html",
window.isMobileDevice ? "text!views/tools/templates/i_txtsItem.html" : "text!views/tools/templates/txtsItem.html",
"text!views/tools/templates/fontItem.html",
"curvetext"
],
function ($, Backbone, Config, Model, Collection, ToolsBase, ToolsTmpl, EditorTmpl, TxtTmpl, TxtItemTmpl, FontItemTmpl) {
"use strict";
var View = ToolsBase.extend({
initialize: function() {
var self = this;
if (window.isMobileDevice) {
$(window).bind("resize.app", _.bind(this.resizeTools, this));
}
},
render: function() {
var self = this, tpl_data, tools_tpl_data;
$('.customtool-title .tools-tabs').show();
self.stickerSetup();
//console.log(app.ctors);
tools_tpl_data = {
tips: app.settings.tips,
isCompetition: app.settings.competition !== undefined,
allowCodes: app.ctors["toolsCtor"].getAllowCodes(),
customType: 'stamper'
};
if (app.settings.competition !== undefined) {
tools_tpl_data.competition = app.settings.competition
}
console.log(ToolsTmpl);
self.$el.find(".tools").append(_.template(ToolsTmpl, tools_tpl_data));
tpl_data = {
stickerTxtTop : self.selectedTxt.top,
stickerTxtMiddle : self.selectedTxt.middle,
stickerTxtBottom : self.selectedTxt.bottom,
selectedtitle : self.selectedTitle,
selectedtemplate : self.selectedTemplate,
stickerTemplate : Config.templates + self.selectedTemplate + Config.templateExtension,
isCompetition : app.settings.competition !== undefined,
designType: app.ctors["toolsCtor"].getDesignType(),
tips: app.settings.tips,
selectedCodes : self.selectedCodes,
selectedPoints : self.selectedPoints
};
if (app.settings.competition !== undefined) {
tpl_data.competition = app.settings.competition;
}
if (self.backgroundType === "color") {
tpl_data.stickerBgImage = null;
tpl_data.stickerFgImage = this.getFgPath(self.stickerFgImage);
self.$el.find(".editor").append(_.template(EditorTmpl, tpl_data));
$(".customtool-background").hide();
$('.customtool-fill').css({
background: self.stickerBgColor,
opacity: self.stickerBgOpacity
}).show();
} else {
tpl_data.stickerFgImage = this.getFgPath(self.stickerFgImage);
tpl_data.stickerBgImage = this.getBgPath(self.stickerBgImage);
self.$el.find(".editor").append(_.template(EditorTmpl, tpl_data));
$(".customtool-background").show();
$('.customtool-fill').hide();
}
self.applyTextFormatting();
self.refreshArcs(1,".customtool-toptext", self.selectedTxt.top.arc);
self.refreshArcs(2,".customtool-middletext", self.selectedTxt.middle.arc);
self.refreshArcs(3,".customtool-bottomtext", self.selectedTxt.bottom.arc);
self.toggleCodes();
if (app.settings.competition !== undefined && !window.isMobileDevice) {
$('#dialog-form').dialog({
autoOpen: false,
width: 600,
modal: true,
zIndex: 1001,
dialogClass: 'competition-dialog',
draggable: false,
buttons: [{
'text': "Create Another",
'class': 'pull-right createanother',
'style': 'display:none',
'click': function(e) {
self.restart(e);
return false;
}
}, {
'text': "Enter Competition",
'class': 'pull-right green enter',
'disabled': true,
'click': function(e) {
self.competitionEnter(e);
return false;
}
}, {
'text': "Order",
'class': 'pull-right continue green',
'style': 'display:none',
'click': function(e) {
self.competitionContinue(e);
return false;
}
}, {
'text': "Cancel",
'class': 'pull-left cancelcomp',
'click': function(e) {
self.competitionCancel(e);
return false;
}
}]
});
}
if (app.settings.competition !== undefined) {
_gaq.push(['_trackPageview', '/sticker-competition/editor']);
}
if (!window.isMobileDevice) {
app.trigger("tools:bg");
}
}
}, {
sticker_id: null,
toolsOpen: false
});
return View;
});

Unable to create a delete button in Meteor using reactive-table

I building a sortable table in Meteor with Reactive-Table and having trouble getting my delete button to work for removing entries from the table.
Please see my javascript code below:
Movies = new Meteor.Collection("movies");
if (Meteor.isClient) {
Template.body.events({
"submit .new-movie": function (event) {
var title = event.target.title.value;
var year = event.target.year.value;
var genre = event.target.genre.value;
Movies.insert({
title: title,
year: year,
genre: genre
});
event.target.title.value = "";
event.target.year.value = "";
event.target.genre.value = "0";
return false;
}
});
Template.moviestable.events({
"click .deletebtn": function (event) {
Movies.remove(this._id);
}
});
Template.moviestable.helpers({
movies : function () {
return Movies.find();
},
tableSettings : function () {
return {
showFilter: false,
fields: [
{ key: 'title', label: 'Movie Title' },
{ key: 'year', label: 'Release Year' },
{ key: 'genre', label: 'Genre' },
{ key: 'edit', label: 'Edit', fn: function () { return new Spacebars.SafeString('<button type="button" class="editbtn">Edit</button>') } },
{ key: 'delete', label: 'Delete', fn: function () { return new Spacebars.SafeString('<button type="button" class="deletebtn">Delete</button>') } }
]
}
}
});
}
Can anyone tell me what I'm doing wrong?
In the reactive tables docs, there's an example of how to delete rows from the table. Adapting the example in the docs for your needs, your event should look like this:
Template.moviestable.events({
'click .reactive-table tbody tr': function (event) {
event.preventDefault();
var objToDelete = this;
// checks if the actual clicked element has the class `deletebtn `
if (event.target.className == "deletebtn") {
Movies.remove(objToDelete._id)
}
}
});
The problem you are having is that you are trying to find the _id property on the button click instead of the row click.
If you do console.log(this) on your button click event (as you have it in your question above) you will get something like this Object {key: "delete", label: "", fieldId: "2", sortOrder: ReactiveVar, sortDirection: ReactiveVar} which does not contain the property _id
It is easier to register the row click, where the row object is the actual document you are trying to delete, and then check if the event's target has the delete class you added.

How can I check if Shift+Enter is pressed on a textarea

I want to submit the form if Enter is pressed and stop the event if Shift + Enter is pressed. The callback for this has Ext.EventObject parameter which does not provide any way to check if shiftkey is pressed.
it has two methods .hasModifier and .isSpecialKey. Both returns boolean. There is no way to find if shiftkey is pressed. how do I trace it?
This is my textarea component:
{
region : 'center',
margins : '5 0 0 0',
xtype : 'textarea',
name : 'chatmessage',
enableKeyEvents: true,
listeners: {
keydown: function(textfield, evt, eOpts){
console.log(evt.getKey());
}
}
}
I tried evt.shiftKey. Its undefined.
This can be done with little trick with keydown and keyup events a flag.
listeners : {
keydown : function(tf, e, opt) {
if (e.getKey() == e.SHIFT) {
this.shiftKeyPressed = true; // a flag
return;
}
if (e.getKey() != e.ENTER && (this.shiftKeyPressed == undefined || (this.shiftKeyPressed == false))) {
// Submit form
e.stopEvent();
}
},
keyup : function(tf, e, eOpts) {
if (e.getKey() == e.SHIFT) {
this.shiftKeyPressed = false;
}
}
}
Why dont you use a keymap ( http://docs.sencha.com/ext-js/4-1/#!/api/Ext.util.KeyMap ) on your textarea? Can't test the code here but should be something like this:
var textArea= Ext.create('Ext.form.field.TextArea', {
region : 'center',
margins : '5 0 0 0',
xtype : 'textarea',
name : 'chatmessage',
enableKeyEvents: true
});
var map = new Ext.util.KeyMap({
target: textArea,
binding: [{
key: Ext.EventObject.ENTER,
fn: function(){ alert('Enter pressed!'); }
}, {
key: Ext.EventObject.ENTER,
shift:true,
fn: function(){ alert('Shift+ENTER pressed!'); }
}]
});

How to get Ext JS component from DOM element

Trying to create an inline edit form.
I have a form that looks like this:
var editPic = "<img src='https://s3.amazonaws.com/bzimages/pencil.png' alt='edit' height='24' width='24' style='margin-left: 10px;'/>";
var submitPic = "<img id='submitPic' src='https://s3.amazonaws.com/bzimages/submitPic.png' alt='edit' height='24' width='24'/>";
Ext.define('BM.view.test.Edit', {
extend: 'Ext.form.Panel',
alias: 'widget.test-edit',
layout: 'anchor',
title: 'Edit Test',
defaultType: 'displayfield',
items: [
{name: 'id', hidden: true},
{
name: 'name',
fieldLabel: 'Name',
afterSubTpl: editPic,
cls: 'editable'
},
{
name: 'nameEdit',
fieldLabel: 'Name',
xtype: 'textfield',
hidden: true,
cls: 'editMode',
allowBlank: false,
afterSubTpl: submitPic
}
]
});
The controller looks like this (a lot of events):
init: function() {
this.control({
'test-edit > displayfield': {
afterrender: this.showEditable
},
'test-edit': {
afterrender: this.formRendered
},
'test-edit > field[cls=editMode]': {
specialkey: this.editField,
blur: this.outOfFocus
}
});
},
outOfFocus: function(field, event) {
console.log('Lost focus');
this.revertToDisplayField(field);
},
revertToDisplayField: function(field) {
field.previousNode().show();
field.hide();
},
formRendered: function(form) {
Ext.get('submitPic').on('click', function (event, object) {
var field = Ext.get(object).parent().parent().parent().parent();
var cmp = Ext.ComponentQuery.query('test-edit > field[cls=editMode]');
});
},
editField: function(field, e) {
var value = field.value;
if (e.getKey() === e.ENTER) {
if (!field.allowBlank && Ext.isEmpty(value)){
console.log('Not permitted!');
} else {
var record = Ext.ComponentQuery.query('test-edit')[0].getForm().getRecord();
Ext.Ajax.request({
url: '../webapp/tests/update',
method:'Post',
params: {
id: record.getId(),
fieldName: field.name,
fieldValue: field.value
},
store: record.store,
success: function(response, t){
field.previousNode().setValue(value);
t.store.reload();
var text = response.responseText;
// process server response here
console.log('Update successful!');
}
});
}
this.revertToDisplayField(field);
} else if (e.getKey() === e.ESC) {
console.log('gave up');
this.revertToDisplayField(field);
}
},
showEditable: function(df) {
df.getEl().on("click", handleClick, this, df);
function handleClick(e, t, df){
e.preventDefault();
var editable = df.nextNode();
editable.setValue(df.getValue());
editable.show();
editable.focus();
df.hide();
}
},
I'm using the 'afterSubTpl' config to add the edit icon, and the accept icon.
I have listeners set up to listen on click events concerning them, but after they are clicked, I only have the element created by Ext.get('submitPic'). Now I want to have access to the the Ext field and form that surround it. The parent method only brings back other DOM elements. How do I connect between them? You can see what I tried in formRendered.
I hope someone can clarify this little bit for me.
Walk up the DOM tree until you find a component for the element's id:
getCmpFromEl = function(el) {
var body = Ext.getBody();
var cmp;
do {
cmp = Ext.getCmp(el.id);
el = el.parentNode;
} while (!cmp && el !== body);
return cmp;
}
Ext.Component.from(el) does exactly this since ExtJS 6.5.0, as I just learnt. Doc
Source
You can get the component by id, but only if your component and its dom element have the same id (they usually do):
Ext.getCmp(yourelement.id)
But this is not exactly good practice -- it would be better to set up your listeners so that the handler methods already have a reference to the component. For example, in your 'submitPic' component, you could define the click listener like this:
var me = this;
me.on({
click: function(arguments){
var cmp = me;
...
});

Categories

Resources