Reusable Action in Ext JS MVC - extjs

I have a Grid Panel with a toolbar and an context menu.
The toolbar has a edit button and the context menu has a edit menu item.
Both shares the same properties (text, icon and handler)
Ext has something called Action which makes it possible to share functionality etc. between components, but til now I have had no success getting it to work in the MVC architecture
(I am using the new MVC architecture in 4.0)
My Action class looks like this:
Ext.define( 'App.action.EditAction', {
extend: 'Ext.Action',
text: 'Edit',
handler: function()
{
Ext.Msg.alert('Click', 'You did something.');
},
iconCls: 'icon-edit-user' ,
});
And in my context menu
requires: ['App.action.EditAction'],
initComponent: function()
{
var editUser = new App.action.EditAction();
this.items = [
editUser,
{
// More menuitems
}
...
];
this.callParent(arguments);
When running the code I get "config is undefined" in the console.
Can anyone point out what I am doing wrong?
Thanks in advance,
t

Passing an empty config to your constructor will avoid the error, but have unwanted consequences later because, unfortunately, the base class (Ext.Action) relies on this.initialConfig later on. For example, if you called editUser.getText() it would return undefined instead of the expected 'Edit'.
Another approach is to override your constructor to allow a no-arg invocation and apply your overridden configuration:
Ext.define( 'App.action.EditAction', {
extend: 'Ext.Action',
text: 'Edit',
constructor: function(config)
{
config = Ext.applyIf(config || {}, this);
this.callParent([config]);
},
handler: function()
{
Ext.Msg.alert('Click', 'You did something.');
},
iconCls: 'icon-edit-user' ,
});

As per Ext.Action constructor
constructor : function(config){
this.initialConfig = config;
this.itemId = config.itemId = (config.itemId || config.id || Ext.id());
this.items = [];
}
You must supply config not to get config is undefined exception in the second line (precisely in config.itemId part).
Updating your code as var editUser = new App.action.EditAction({}); should help(passing new empty object as config).
Surely, you could add some properties to the config object too.

Related

ExtJS cannot override methods statics

I wanted to extend Ext.Action class due to add my own methods, but I've encouraged problem Cannot override method statics on Core.app.Action instance.
I know that is a problem connected to overriding constructor. But don't know how to solve it other way.
Here is code of my component
Ext.define('Core.app.Action', {
extend: 'Ext.Action',
iconCls: 'icon-add',
currentData: undefined,
constructor: function(config){
config = Ext.applyIf(config || {}, this);
this.callParent([config])
},
handler: function (widget, event) {
Ext.Msg.alert("Name:", this.currentData.data.company)
},
getActionId: function () {
return this.actionId
},
setCurrentData: function (data) {
this.currentData = data
this.disable()
if (data.data.actions) {
this.currentData.data.actions.forEach(action => {
if (action === this.actionId) this.enable()
})
}
}
})
And there is a way how I create instance of mentioned class
Ext.create('Core.app.Action', {
actionId: 'D',
text: "Action D",
})
ExtJS is not throwing errors when I remove constructor from my class, but I can't also use methods such as handler or setCurrentData.
I've also tried overriding the component, but failed.
Answers in solution below weren't helpful in this case.
Reusable Action in Ext JS MVC

Listen for other components events

I am developing a component that act as an application taskbar.
Currently, I have a class App (that's not the fully qualified class name) that extends Ext.window.Window which on init it creates a button with reference to itself and renders it to the taskbar. But I don't think this is the application's responsibility to add itself to the taskbar, but rather it is the taskbar's responsibility to listen for applications initialization and create a reference to them in it.
So, in the taskbar's ViewController I need to capture all the render events fired by any App instance. I can't find a way to do that in the documentation.
How can I do it? Or is there a better way of doing it?
ExtJS 5.1
Define an Ext.app.EventDomain to monitor Ext.window.Window events.
Ext.define('MyApp.app.domain.Taskbar', {
extend: 'Ext.app.EventDomain',
singleton: true,
requires: [
'Ext.window.Window'
],
// catalog the domain in the Ext.app.EventDomain.instances map
type: 'taskbar',
idProperty: 'id',
constructor: function() {
this.callParent();
this.monitor( Ext.window.Window );
}
})
Define a controller to listen for the window render event.
Ext.define('MyApp.controller.Taskbar', {
extend: 'Ext.app.Controller',
requires : [
'MyApp.app.domain.Taskbar'
],
init: function() {
this.listen({
taskbar: {
// wildcard selector to match any window
'*':{
render: function(window, eOpts){
console.log('render window: ' + window.id);
}
}
}
})
}
})

ExtJS Class constructor

I have a custom class created
Ext.define('MyFormPanel, {
extend: 'Ext.form.Panel',
field1: null,
field2: null
constructor: function (config) {
this.createFields();
config.items.splice(0, 0, [
this.field1,
this.field2
]
this.callParent([config]);
}
});
However it will not add my fields to the form. However, if I swap at the config.items.splice for
config.items[0] = this.field1;
config.items[1] = this.field2;
The form panel is created correctly.
My question is am I using the splice command incorrectly? Is there an alternative?
You are not using splice correctly. It takes the elements to add as separate arguments, not an array
There are other problems:
Name of class in missing a quote to close it
Your call to splice is not closed, missing a )
You have to make sure items is an array before you can call splice on it
Config options have not been copied to this yet.
Try the following https://fiddle.sencha.com/#fiddle/8ij
Ext.define('MyFormPanel', {
extend: 'Ext.form.Panel',
field1: null,
field2: null
constructor: function (config) {
this.createFields();
config.items = config.items || [];
config.items.splice(0, 0, config.field1, config.field2);
this.callParent([config]);
}
});
You should not override constructor. You should override initComponent
Ext.define('MyFormPanel', {
extend: 'Ext.form.Panel',
field1: null,
field2: null
initComponent: function () {
this.createFields();
this.items = this.items || [];
this.items.splice(0, 0, this.field1, this.field2);
this.callParent();
}
});
From a readability perspective it makes it very hard to determine what your constructor is trying to do. Some improvements:
Move all the legwork to create fields into the initComponent as Juan recommends. This includes any dependencies on the fields in the current constructor to the parent initComponent.
You need to start invoking the super method with the special JavaScript reserved word "arguments" (as opposed to [config]) this will call another method with the argument signature which invoked the current method.
Pretty sure the only time you should need to override constructor instead of initComponent is when you are working from custom classes which don't extend off any component.
Why aren't you able to use the Panel#add() method to add your fields in initComponent? Splice feels hacky given the Ext API's allow you to add fields directly.
Ext.define('MyFormPanel, {extend: 'Ext.form.Panel',
initComponent: function () {
this.callParent(arguments);
this.createFields();
},
createFields : function() {
this.field1 = Ext.create('YourField1', {});
this.add(this.field1);
this.field2 = Ext.create('YourField2', {});
this.add(this.field2);
}});

getRootNode() is not a function

I try to develop an app with MVC architecture. I've the following Controller code:
Ext.define('PM.controller.Projects', {
extend: 'Ext.app.Controller',
models: ['Project'],
stores: ['Projects'],
views: [
'projects.Tree',
'Toolbar',
],
init: function(config) {
var tree = this.getProjectsTreeView();
var rootNode = tree.getRootNode();
console.log(rootNode);
this.callParent(config);
}
});
And this view code:
Ext.define('PM.view.projects.Tree', {
extend: 'Ext.tree.Panel',
xtype: 'projectsTree',
title: 'Projects',
hideHeaders: true,
root: {
text: "Projekte"
}
});
It try to get the root node from my tree view in the controller but I get the error that getRootNode() is not a valid function in my controller. Can anybody tell me why I get this error? My target is to add new children to this root node from an ajax request.
Thanks
The methods Ext generates for each string in the views array return constructors that can be used to create the respective views. That seems bizarre, but that's how it is.
If you want to access the actual view component, you'll need to create a ref for it. Your init method should not assume that the view exists yet. It's very likely that it won't since the controller's init method is called before the application's launch method which is probably where all the views are getting added to the page.
You want to put your logic in the controller's onLaunch template method which is called after the application has been launched and your view has been added.
Ext.define('PM.controller.Projects', {
extend: 'Ext.app.Controller',
refs: [{
ref: 'projectsTreeView',
selector: 'projectsTree'
}],
init: function() {
// It's safe to add selectors for views that don't exist yet.
this.control(/*...*/)
},
onLaunch: function(config) {
var tree = this.getProjectsTreeView();
var rootNode = tree.getRootNode();
console.log(rootNode);
}
});
If this doesn't work, that means you aren't actually adding your view anywhere. One place you could add it is in the application's launch method. Something has to add the treeview.
Ext.application({
// ...
views: ['projects.Tree']
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [new this.getProjectsTreeView()]
});
}
});
So the chronology of events is this:
Application#constructor
Controller#constructor
Controller#init (can't assume the view exists)
Application#onBeforeLaunch
Application#launch (view is now added)
Controller#onLaunch (do something with the view that is now available)
Also, your view alias may need to be 'widget.projectsTree' not just 'projectsTree'.

In ExtJS components how to forward config: {} items to sub components

I am trying to write a reusable item selection panel where the user has a grid with items he can choose from and a small text field that he can use to filter the content of the grid. Right now the (simplified) view code looks like this and works.
Ext.define('MyApp.view.items.ItemSelectorPanel', {
extend: 'Ext.panel.Panel',
require: 'MyApp.view.items.SimpleItemGrid',
alias: 'widget.ItemSelectorPanel',
layout: 'form',
config: {
itemStore: false
},
constructor: function(config) {
this.initConfig(config);
this.superclass.constructor.call(this, config);
this.add([
{
fieldLabel: 'Filter',
name: 'filter'
},
{
xtype: 'SimpleItemGrid',
collapsible: true,
store: this.getItemStore()
}
]);
return this;
}
});
As you can see the ItemSelectorPanel uses the config property to expose an interface where the calling site can specify which item store to use.
Calling site (in this case the panel is added to a TabPanel):
var panelToAdd = {
xtype: 'panel',
title: 'New Selection',
closable: true,
padding: 10,
items: [{
title: 'Select node',
xtype: 'ItemSelectorPanel',
itemStore: itemStore
}]
};
Now, I love the declarative style of ExtJS 4 and how it helps to follow the MVC pattern. I would prefer to have the least amount of code possible in the views. Unfortunately this does not work:
Ext.define('MyApp.view.items.ItemSelectorPanel', {
/* ... same as above ... */
constructor: function(config) {
this.initConfig(config);
this.superclass.constructor.call(this, config);
return this;
},
items: [
{
fieldLabel: 'Filter',
name: 'filter'
},
{
xtype: 'SimpleItemGrid',
collapsible: true,
store: this.getItemStore // <-- interesting part
}
]
});
Is there a way to expose the config of a nested/sub component via the config property of the parent property in a declarative manner?
First something in general
Never add an object outside a function within a class definition unless you exactly know what you are going to do. Cause if you do so all instances will share the same instance of that object. I think I do not need to mention where this leads to...
If you have a need to place a object there you should clone it within the constructor.
To your code
I dunno what this.initConfig(config); does but the config variable is not the one from your class, it is the one from the constructor argument. I recommend you also to use initComponent() for initialization instead of the constructor() unless you have a defined need for using the constructor, which in your case you don't seem to have.
Also a 'config' is not forwarded cause it don't get executed up->bottom but bottom->up where a config get's hand up and all other properties are (already) inherited.
I still do not exactly know what your goal is, therefore I cannot give you any advice how you should do this but I can say for sure that the way you do it will lead to problems.
Edit
I still not sure that I have fully understand your needs but the following should work (if you need the listeners too you might take a look at the Ext.util.Bindable mixin)
Ext.define('MyApp.view.items.ItemSelectorPanel', {
extend: 'Ext.panel.Panel',
require: 'MyApp.view.items.SimpleItemGrid',
alias: 'widget.ItemSelectorPanel',
layout: 'form',
initComponent: function() {
// Initialize the store (might be a instance or a storeId)
var store;
if (this.itemStore) {
store = Ext.data.StoreManager.lookup(store);
}
this.itemStore = store || null;
// Add is not valid (at least not before the parent inits are executed)
this.items = [{
fieldLabel: 'Filter',
name: 'filter'
}, {
xtype: 'SimpleItemGrid',
collapsible: true,
store: this.getItemStore()
}];
this.callParent(arguments);
},
getItemStore: function() {
return this.itemStore;
}
});
No, you can't do it in the way you've described. The reason is pretty simple, let's take this as an example:
Ext.define('MyClass', {
someProp: this.foo(),
foo: function(){
return bar;
}
});
Here, we call the define() method and we pass it an object as the configuration. As such, the whole object (including the call to foo()) is evaluated before it's even passed to define, so the class/method doesn't even exist at that point.
Even if you could do that, here's also the complication that foo is an instance method on the class, but the way you're attempting to call it is as though it's a static method.
So, the answer is, you'll need to use some kind of method to do so, initComponent is typically preferred over the constructor.
You can define items in declaration of your class but you cannot call any method from your class at time of declaration. To solve it, define only items without store and than use initComponent method to set store for your view.
I didn't see an answer that addressed the original question. Here is what I've found to work ...
Creating an instance of myClass, passing in a config 'foo' with value 'bar'
var myClassInstance = Ext.create('MyApp.view.myClass', {
foo: 'bar'
});
myClass is defined as follows :
Ext.define('MyApp.view.myClass', {
extend: 'Ext.container.Container',
alias: 'widget.myclass',
config: {
foo: 'defaultVal'
},
constructor: function(configs) {
this.callParent(arguments); //create class, calls initComponent
var try1 = getFoo(); //try1 is 'defaultVal'
this.initConfig(configs); //initializes configs passed in constructor
var try2 = getFoo(); //try2 is 'bar'
},
initComponent: function() {
//myClass declaration here ...
this.callParent();
}

Resources