Ext.bind does not see function in ExtJS - javascript

I am trying to mod the Portlet example and port it into our program. The code looks like this:
Ext.create('Ext.container.Viewport',{
id: 'app-viewport', //creates viewport
layout: {
type: 'border',
padding: '0 5 5 5' // pad the layout from the window edges
},
onPortletClose: function(portlet) {
this.showMsg('"' + portlet.title + '" was removed');
},
showMsg: function(msg) {
var el = Ext.get('app-msg'),
msgId = Ext.id();
this.msgId = msgId;
el.update(msg).show();
Ext.defer(this.clearMsg, 3000, this, [msgId]);
},
clearMsg: function(msgId) {
if (msgId === this.msgId) {
Ext.get('app-msg').hide();
}
},
items: [{
id: 'app-header',
xtype: 'box',
region: 'north',
height: 40,
html: 'Ext Welcome'
},{
xtype: 'container',
region: 'center',
layout: 'border',
items: [{
id: 'app-options', //Creates the Options panel on the left
title: 'Options',
region: 'west',
animCollapse: true,
width: 200,
minWidth: 150,
maxWidth: 400,
split: true,
collapsible: true,
layout:{
type: 'accordion',
animate: true
},
items: [{
html: content,
title:'Navigation',
autoScroll: true,
border: false,
iconCls: 'nav'
},{
title:'Settings',
html: content,
border: false,
autoScroll: true,
iconCls: 'settings'
}]
},{
id: 'app-portal', //Creates the panel where the portal drop zones are.
xtype: 'mainpanel',
region: 'center',
items: [{
id: 'col-1', //Each column represents a drop zone column. If we add more there are more created and width gets adjusted accordingly
items: [{
id: 'portlet-1',
title: 'Portlet 1',
html: content,
listeners: {
'close': Ext.bind(this.onPortletClose, this)
},{
id: 'portlet-2',
title: 'Portlet 2',
html: content,
listeners: {
'close': Ext.bind(this.onPortletClose, this)
}
}]
},{
id: 'col-2',
items: [{
id: 'portlet-3',
title: 'Portlet 3',
html: content,
listeners: {
'close': Ext.bind(this.onPortletClose, this)
}
}]
},{
id: 'col-3',
items: [{
id: 'portlet-4',
title: 'Portlet 4',
html: content,
listeners: {
'close': Ext.bind(this.onPortletClose, this)
}
}]
}]
}]
}]
});
The problem is that Ext.bind cannot read the onPortletClose function and the browser gives me a:
Uncaught TypeError: Cannot read property 'apply' of undefined error. I checked the stack and essentially in the Ext.bind(fn,scope) the fn is undefined and thus it cannot read the handler function. The difference between my application and in the example is that I add this directly into a JSP's Ext.onReady() whereas in the example all of this is added through a Ext.apply(this, {...}). I'm really confused. I tried all kinds of gimmicks to force the scope on the viewport but it seems that whatever is inside Ext.bind() loses contact with outside or something. I've used Ext.bind() before and it went fine although it was inside an initComponent configuration. Is that mandatory? If no then what is the problem?

It is important to understand the meaning of this here (or in general when working with JavaScript or ExtJS).
In a global context, this refers to the global object, also known as the global window variable. This is the case inside your Ext.onReady function:
Ext.onReady(function() {
console.log(this === window);
// -> true
// because this is the global object
});
In an object context, by default this refers to the owner object of the function (there are ways around it and actually this is exactly want you want do achieve using Ext.bind):
var obj = {
prop: 'My text property',
fn: function() {
console.log(this.prop);
// -> My text property
// because "this" refers to our object "obj"
}
};
Now, this is exactly what makes the difference between your case and the one from the examples.
When using the approach with Ext.onReady this - as pointed out above - will refer to the global object, which of course does not have a function onPortletClose.
When using the approach from the examples, this is accessed from inside of initComponent, which is a member function of your derived viewport class, and therefore this refers to the component instance (= the owning object), which allows you to access your function.
Ext.define('MyViewport', {
extend: 'Ext.container.Viewport',
onPortletClose: function(portlet) {
this.showMsg('"' + portlet.title + '" was removed');
},
initComponent: function() {
console.log(this);
// -> the instance of your viewport class
Ext.apply(this, {
items:[{
xtype: 'panel',
title: 'Portlet 1',
listeners: {
'close': Ext.bind(this.onPortletClose, this)
}
}]
});
this.callParent();
}
});
Side notes
Ext.apply
Ext.apply really just copies all properties from one object to another, so in this case it is just a convenient way of applying all attributes of that object to this with one function call. You could as well just use:
this.items = [...];
Changing the scope of your listeners
You do not need to use Ext.bind when adding listeners to a component, you can simply provide a scope configuration in your listeners object:
listeners: {
close: function() {...},
scope: this
}
External sources
If you want to dive in a little deeper (which I would recommend), you might want to read more about this at the MDN (Mozilla Developer Network).

Related

Problems with references and stores in Sencha ExtJS

I’m new here in at Stackoverflow and to Sencha ExtJS development. I’m a student from Germany and I’m current trying to get my degree in media computer sciences. As a part of my final assignment I’m currently developing the UI of a webapp for a local company.
While I was trying out the capabilities of the Sencha ExtJS framework I came across some problems, which is why I’m now reaching out to the community for help ;)
My first problem I had, was when I was playing around with the syntax for instancing classes using xtypes and the association of Stores inside the ViewModel:
For the purpose of easier to read and less cluttered code I wanted to give my stores their own xtype so I could instead of declaring all the stores and their configs inside the ViewModels’ stores config wanted to have every store inside their own file and then just create an instance of them later inside the ViewModel. The code I wrote for this looks like this:
ViewModel:
Ext.define('Example.viewmodel.MyViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.myviewmodel',
requires: [
'Example.store.MyStore',
],
stores: {
StoreA: { xtype: 'store_a' },
StoreB: { xtype: 'store_b' },
StoreC: { xtype: 'store_c' }
},
data: {
/* This object holds the arbitrary data that populates the ViewModel and
is then available for binding. */
}
});
StoreA:
Ext.define('Example.store.StoreA', {
extend: 'Ext.data.Store',
xtype: 'store_a',
requires: [
'Example.model.ModelA'
],
storeId: 'StoreA',
autoLoad: false,
model: 'Example.model.ModelA',
listeners: {
load: 'onLoadofStoreA'
}
});
But apparently this isn’t working… My load listener of the store does not seem to fire at the method inside my controller and does not even seem to know about the view that is associated with the ViewModel. What am I doing wrong or is this just not meant to be done like that?
My Second Problem was when I was playing around with some of the UI components. My scenario was like this:
I wanted to have a menu that would slide in, where u could do some inputs that would then load the content for the view.
I found this example for a sliding menu (https://examples.sencha.com/extjs/6.7.0/examples/kitchensink/?modern#menus) and built this:
Inside my ViewController:
getMenuCfg: function (side) {
var cfg = {
side: side,
controller: example_controller',
id: 'topMenu',
items: [
{
xtype: 'container',
layout: 'hbox',
width: '100%',
items: [
{
xtype: 'fieldset',
reference: 'fldSet',
id: 'fldSet',
layout: 'vbox',
width: '50%',
defaults: {
labelTextAlign: 'left'
},
items: [
{
autoSelect: false,
xtype: 'selectfield',
label: 'Selectfield',
reference: 'sfExample',
id: 'sfExample',
listeners: {
change: 'onSFChange'
}
},
{
xtype: 'container',
layout: {
type: 'hbox',
align: 'end',
pack: 'center'
},
items: [{
xtype: 'textfield',
reference: 'ressource',
id: 'ressource',
flex: 1,
textAlign: 'left',
margin: '0 10 0 0',
label: 'Ressource',
labelAlign: 'top',
labelTextAlign: 'left',
editable: false,
readOnly: true
},
{
xtype: 'button',
shadow: 'true',
ui: 'action round',
height: '50%',
iconCls: 'x-fa fa-arrow-right',
handler: 'openDialog'
}
]
},
{
xtype: 'textfield',
reference: 'tfExample',
id: 'tfExample',
label: 'Textfield',
editable: false,
readOnly: true
}
]
},
}]
}];
The problem I come across now is, that I would no longer be able to easily get the references of components inside the menu (input fields) with this.lookupReference() as if they were just part of the view. In fact to find a workaround I had to trace a way back to the components using a debugger.
For example if another method inside my controller wanted to use a field inside this menu, instead of simply just doing this.lookupReference(‘sfExample’) I now had to do something like this:
var me = this,
vm = me.getViewModel(),
menuItems = me.topMenu.getActiveItem().getItems(),
fieldset = menuItems.getByKey('fldSet'),
selectfieldRessArt = fieldsetLeft.getItems().getByKey('sfExample');
I’m pretty sure that I am missing out on something important here and there has to be a way to do this easier. I’m really looking forward to your answers, thank you in advance ;)
use xtype only for components. if you need to define an type/alias for store, use alias config property instead and especify the alias category "store.".
Defining a store with an alias
Ext.define('Example.store.StoreA', {
extend: 'Ext.data.Store',
//use store. to category as a store
alias: 'store.store_a',
requires: [
'Example.model.ModelA'
],
storeId: 'StoreA',
autoLoad: false,
model: 'Example.model.ModelA',
listeners: {
load: 'onLoadofStoreA'
}
});
Instantianting your store by type
Ext.define('Example.viewmodel.MyViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.myviewmodel',
requires: [
'Example.store.MyStore',
],
stores: {
StoreA: { type: 'store_a' },
StoreB: { type: 'store_b' },
StoreC: { type: 'store_c' }
},
data: {
/* This object holds the arbitrary data that populates the ViewModel and
is then available for binding. */
}
});
I Hope it can help you

EXTjs getEl() fails before showing the element

Good day all.
In EXTjs, probably 4.x version, I have a menu with a couple of levels of sub-menus
I'd like to add a data attribute to some of those sub-menus and actually I can do this with no problems with:
Ext.getCmp("notificationMenu").getEl().set({"data-notifynumber": 4});
but this is working only for the first element of the menu (to be clear, the element that is shown upon loading.
For any other element of the menu, first of all I have to click the menu to show all the sub-menu and only at that time I can use the getEl() function, otherwise this error is shown:
Uncaught TypeError: Cannot read property 'set' of undefined
I understand that I'd need to... show? render? well, "do something" to those sub elements in order to have them in the dom properly... I attach part of the code:
this is part of the menu I create:
xtype: 'button',
id:"notificationMenu",
hidden: false,
reference: 'userType',
style: 'color: #ffffff;width:58px;height:58px;',
glyph: 0xf0f3,
menu:{
border:0,
menuAlign: 'tr-br?',
bodyStyle: {
background: '#3e4752',
},
items:[
{
text:"TASKS",
disabled:true
},
{
text:"Campaigns",
data_id:"me_campaigns",
glyph:0xf0c1,
id:"notification_me_campaigns_root",
hidden:true,
menu:{
border:0,
menuAlign: 'tr-br?',
bodyStyle: {
background: '#3e4752',
},
items:[
{
text:"Approval",...
in this example, if I make after Render:
Ext.getCmp("notificationMenu").getEl().set({"data-notifynumber": 10})
but if I use
Ext.getCmp("notification_me_campaigns_root").getEl().set({"data-notifynumber": 4})
the error above is shown. please do you have some advice? may I call a "force render" somehow?
Try to use afterrender to get dom element.
ExtJs getEl() Retrieves the top level element representing this component but work when dom is prepared without dom creation it will return null.
I have created an Sencha Fiddle demo hope this will help you to achieve you requirement/solution.
var panel = new Ext.panel.Panel({
renderTo: document.body,
title: 'A Panel',
width: 200,
tools: [{
xtype: 'button',
text: 'Foo',
menu: {
defaults: {
handler: function () {
Ext.Msg.alert('Successs', 'You have click on <b>data-notifynumber</> ' + this.up('menu').getEl().getAttribute('data-notifynumber'))
}
},
items: [{
text: 'Item 1'
}, {
text: 'Item 2',
menu: {
listeners: {
afterrender: function () {
this.getEl().set({
"data-notifynumber": 20//only for example you can put as basis of your requirement
});
}
},
defaults: {
handler: function () {
Ext.Msg.alert('Successs', 'You have click on <b>data-notifynumber</> ' + this.up('menu').getEl().getAttribute('data-notifynumber'))
}
},
items: [{
text: 'Sub Item 1',
}, {
text: 'Sub Item 2'
}]
}
}],
listeners: {
afterrender: function () {
this.getEl().set({
"data-notifynumber": 10//only for example you can put as basis of your requirement
});
}
}
}
}]
});

html with value from function

Im really new to this java script and Sencha touch so sorry if this question is simple but I didn't find a way to do this.
I have a function that returns a value .
now I want to display the value from the function inside an html line.
how im calling this function from html element? how I show the value?
config: {
title: 'Me',
iconCls: 'user',
//layout: 'fit',
/* create a title bar for the tab panel */
items: [
{
docked: 'top',
xtype: 'titlebar',
title: 'Singers'
},
{
html: [
'<h1>Hi!! ' + this.setName +'</h1>'
].join("")
}
],
},
setName: function (val) {
var store =Ext.getStore('user');
var last = st.last('user');
return val=(last.get('user'));
}
});
You could use the itemId property to reference the component and then update its html property via the initialise listener.
For example:
config: {
title: 'Me',
iconCls: 'user',
//layout: 'fit',
/* create a title bar for the tab panel */
items: [
{
docked: 'top',
xtype: 'titlebar',
title: 'Singers'
},
{
itemId:'htmlContainer', //use itemIds like div ids
xtype:'container',
html: ''
}
],
/**
* #cfg listeners
* Parent Component listeners go here.
* Check sencha touch doc for more information and other available events.
*/
listeners:{
initialize: 'onInitialise'
}
},
onInitialise: function()
{
//set the html config item here
var c = this.down('#htmlContainer');
c.setHtml(this.setName());
},
setName: function (val) {
....
}

Extjs, collapsed form panel. Title not showing up

I have a form panel in a border layout as follows:
{
xtype: 'form',
region: 'north',
split: true,
labelAlign: 'top',
height: 130,
autoScroll: true,
collapsible: true,
listeners: {
'collapse': function () {
Ext.getCmp('slider').setTitle('Filter Events By Time');
// this is not working either
}
},
//collapsed: true,
id: 'slider',
title: 'Filter Events By Time',
border: true,
html: {
tag: 'div',
style: '',
children: [{
tag: 'div',
cls: 'slider_div',
style: 'margin-right:50px;position:relative;float:left'
}, {
tag: 'div',
cls: 'slider_unit',
style: 'margin-top:10px'
}, {
tag: 'div',
style: 'clear:left'
}, {
tag: 'div',
cls: 'startDate',
style: 'margin-right:30px;float:left'
}, {
tag: 'div',
cls: 'endDate',
style: ''
}, {
tag: 'div',
style: 'clear:left'
}]
}
}
Now, when I collapse it using following code, the collapsed panel does not have a title. I can see the title if I expand the panel.
Ext.getCmp('slider').collapse(true);
How can I get title on a collapsed form panel?
There are two small things you need to fix:
1 Method collapse, does not take argument bool, but collapse( [direction], [animate] ), all optional.
2 Use itemId instead of id:
An itemId can be used as an alternative way to get a reference to a
component when no object reference is available. Instead of using an
id with Ext.getCmp, use itemId with
Ext.container.Container.getComponent which will retrieve itemId's or
id's. Since itemId's are an index to the container's internal
MixedCollection, the itemId is scoped locally to the container --
avoiding potential conflicts with Ext.ComponentManager which requires
a unique id.
3 Fetch component reference using this inside of internal scope and use ComponentQuery outside of it. Like this:
this.setTitle('Filter Events By Tim Collapsede');
and/or
Ext.ComponentQuery.query('#slider')[0].collapse();
and also please create your components using Ext.define, and then call them in your border layout using alias/xtype. :-)
Here is a example on fiddle

Declaring functions inside initComponent Ext JS4

Im working on a project using Ext JS4. In some of our classes we are declaring functions inside the initComponent function which may then be set as handlers to a control. I will include an example of this below. Ignore most of what is in the class, the key details are the fact that the Handlers are declared within initComponent and set as handlers to the buttons.
Now, this actually WORKS - the qestion here is WHY this works. I'm fairly new to JavaScript, but I thought that any vars or functions declared within a function were destroyed once that function had completed. Is this incorrect? I appreciate that there may be a better coding style to this, but I would really like to get my head around this before I consider changing loads of classes. The class is as follows... Some comments identify the key areas.
Ext.onReady(function () {
Ext.application({
name: 'Form2',
thisForm: {},
launch: function() {
thisForm = Ext.create('Form2', {});
}
});
});
Ext.define('Form2', {
extend: 'Ext.form.Panel',
layout:'border',
config: {
controlManager: {},
formVariables: {},
dataHelper: {}
},
constructor: function () {
var me = this;
...
...
// Initialize the form - I know, this might not be the be best coding style here.
me.initComponent();
},
initComponent: function() {
Ext.QuickTips.init();
var ButtonControl1 = this.controlManager.createButton('ButtonControl1');
var ButtonControl2 = this.controlManager.createButton('ButtonControl2');
...
...
// Handler for Btton1 - **I'm not using the var keyword in this declaration**
function Handler1() {
alert('This Works!');
};
// Handler for Btton2 - **I'm using the var keyword in this example**
var Handler2 = function () {
alert('This Works also!');
};
// THIS IS THE KEY PART OF THIS QUESTION - even though the handler functions are declared
// locally (above), clicking the buttons will still execute these. Do the functions
// still exist by chance, and will be garbage collected at some later time, or are they
// actually quaranteed to be there. I'm confused!
ButtonControl1.onClickEventHandler = function () {Handler1();};
ButtonControl2.onClickEventHandler = function () {Handler2();};
// Don't need to worry about this part.
Ext.create('Ext.container.Viewport', {
layout:'border',
style: { position:'relative' },
defaults: {
collapsible: true,
split: true,
bodyStyle: 'padding:0px'
},
items: [
{
collapsible: false,
split: false,
region: 'north',
height: 50,
margins: '0 2 0 2',
bbar: '',
items: [ ]
},
{
collapsible: false,
split: false,
region:'west',
margins: '0 0 0 0',
cmargins: '0 2 0 2',
width: 0,
lbar: [ ]
},
{
collapsible: false,
region:'center',
margins: '0 2 0 2',
layout: {
align: 'stretch',
type: 'hbox'
},
items: [
{
xtype: 'form',
fileUpload: true,
layout: {
align: 'stretch',
type: 'vbox'
},
flex: 1,
items: [
{
xtype: 'container',
height: 550,
layout: {
align: 'stretch',
type: 'hbox'
},
items: [
{
xtype: 'container',
width: 570,
layout: 'vbox',
padding: '5 0 0 0',
style:'background-color:rgb(255, 255, 255);',
items: [
ButtonControl1, ButtonControl2
]
}
]
}
]
}
]
}
]
});
}
});
For primitive variables (like string or int), when the function finished all its local variables are distroyed.
For non-primitive variables, the object created locally (such as array or Ext object) will not be distroyed while there is any other object references to it.
In your example ButtonControl1 and ButtonControl2 are declared outside initComponent.
Inside initComponent function, onClickEventHandler is a handler references to Handler1 and Handler2 functions.
When initComponent run finishes, because ButtonControl1 and ButtonControl2 are not in the scope of initComponent (but in the scope of onReady function), they remain to be alive and therefore also all of the objects they are reference to.
var ButtonControl1 = ....; // this global variable object
var ButtonControl2 = ....; // this global variable object
initComponent: function() {
function Handler1() {
...
};
var Handler2 = function () {
...
};
// ButtonControl1 and ButtonControl2 are declared outside of initComponent.
// Unless these variables will be distroyed, they keep onClickEventHandler references to Handler1 and Handler2 objects and therefore these objects will alive outside the scope of initComponent.
ButtonControl1.onClickEventHandler = function () {Handler1();};
ButtonControl2.onClickEventHandler = function () {Handler2();};
}
Consider the last function in the scope of onReady is initComponent (i.e. there is no any other event handler defined).
So why all these objects will remain be alive after initComponent finishes?
The answer is created 'Ext.container.Viewport' object, which is rendered to document's page and therefore all attached objects and reference objects are alive as well.

Categories

Resources