Add logic to Ext.Component initialize Sencha Touch - extjs

I've an application that need to be multilanguage.
The translations comes from the server and are based on the user that is using the application.
My current approach is to create my own field for everything that is used in the app, and during the initialize, I change what it says to the translated text, based on a given code.
For example, in a button, I create my own button like this:
Ext.define('myapp.view.shared.MyButton', {
extend: 'Ext.Button',
xtype: 'myappbutton',
initialize: function () {
this.callParent();
this.setText(myapp.util.Helper.getTranslation(this.textCode, this.defaultText));
}
})
Then I change de default button configuration to something like this, where I just change the xtype, remove text, and add textCode and defaultText.
{
xtype: 'myappbutton',
textCode: 'back',
defaultText: 'Back',
...
}
Then I define the text code and the default text. The getTranslation method, inspects in a local storage to get the translation for the code, and return the finding, or the default text sent.
¡Here is the question!
Since I've 12 different components (so far), and every component extends in some way from Ext.Component, I want to add my code to the initialize of Ext.Component, in order to apply this piece of code, avoiding this crap of creating a custom control for each different control that I need to give translations. Is this possible ?
TIA!
Milton.-

I guess you can always try something along the lines
Ext.define('MyApp.override.Internationalization',{
override:'Ext.Component',
initialize: function () {
me.callOverridden(arguments);
// Your code here.
}
});

Related

Best practice for overriding classes / properties in ExtJS?

I have an Ext.form.field.Text and I want to override the setValue function.
What is the recommended way to override this class functionality in ExtJS? Ext.override?
For clarification:
By real class modification I mean a intended permanent
modification/extension of a class, which should always be done by extending a class.
But it is not a temporary solution for just a specific problem (bug-fix, etc.).
You have at least four options how to override members of (Ext) Classes
prototype I guess is well known and allows you to override a member for all instances of a class. You can use it like
Ext.view.View.prototype.emptyText = "";
While you can't use it like
// callParent is NOT allowed for prototype
Ext.form.field.Text.prototype.setValue = function(val) {
var me = this,
inputEl = me.inputEl;
if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
inputEl.removeCls(me.emptyCls);
me.valueContainsPlaceholder = false;
}
me.callParent(arguments);
me.applyEmptyText();
return me;
};
Here's a JSFiddle
This variant should not be used for real class modifications.
Ext.override does nearly the same then prototype but it fully applies to the ExtJS Class-system which allows you to use callParent()
You can use it like
// callParent is allowed for override
Ext.override('Ext.form.field.Text', {
setValue: function(val) {
this.callParent(['In override']);
return this;
}
});
Here's a JSFiddle (c-p error fixed! Thanks to #nogridbag)
Use case: I faced a (I think still existing) bad behavior of a
radiogroup where ExtJS expect a object (key-value-pair) for correct
setting of the value. But I have just one integer on my backend. I
first applied a fix using Ext.override for the setValue()
method and afterwards extend from radiogroup. There I just make a
Key-Value-Pair from the given value and call the parent method with
that.
As #rixo mentioned this can be used for overriding a instance member. And may therefore be qualified for overriding even mixins (I never tested it myself)
var panel = new Ext.Panel({ ... });
Ext.override(panel, {
initComponent: function () {
// extra processing...
this.callParent();
}
});
This variant should not be used for real class modifications.
Extending a existent class to apply additional behavior & rendering. Use this variant to create a subtype that behaves different without loosing the original type.
In the following example we extend the textfield with a method to change the labelcolor when setting a new value called setColored and override the setValue method to take care of removing a label color when setValue is called directly
Ext.define('Ext.ux.field.Text',{
extend: 'Ext.form.field.Text',
widget: 'uxtextfield',
setColored: function(val,color) {
var me = this;
if (me.settedCls) {
me.removeCls(me.settedCls);
}
me.addCls(color);
me.settedCls = color;
me.setValue(val,true);
},
setValue: function(val,take) {
var me = this;
if (!take && me.settedCls) {
me.removeCls(me.settedCls);
}
me.callParent(arguments);
return me;
}
});
Here's a JSFiddle
Overriding per instance will happen in really rare cases and might not be applicable to all properties. In such a case (where I don't have a example at hand) you have a single need for a different behavior and you might consider overriding a setting just per instance. Basically you do such things all times when you apply a config on class creation but most time you just override default values of config properties but you are also able to override properties that references functions. This completely override the implementation and you might allows don't have access to the basetype (if any exist) meaning you cannot use callParent. You might try it with setValue to see that it cannot be applied to a existing chain. But again, you might face some rare cases where this is useful, even when it is just while development and get reimplemented for productive. For such a case you should apply the override after you created the specific by using Ext.override as mentioned above.
Important: You don't have access to the class-instance by calling this if you don't use Ext.override!
If I missed something or something is (no longer) correct, please comment or feel free to edit.
As commented by #Eric
None of these methods allow you to override mixins (such as Ext.form.field.Field). Since mixin functions are copied into classes at the time you define the class, you have to apply your overrides to the target classes directly
The answer by #sra is great and was very helpful to me in gaining a deeper understanding of the override functionality available in Ext, but it does not include the way that I most commonly implement overrides which looks something like this:
Ext.define('my.application.form.field.Text' {
override: 'Ext.form.field.Text'
getValue: function () {
// your custom functionality here
arguments[1] = false;
// callParent can be used if desired, or the method can be
// re-written without reference to the original
this.callParent(arguments)
}
});
I'm still using Ext 5 so I would then load this file in my Application.js and add it to the requires array there which applies the override to the app globally. I think Ext 6 projects include an override folder and simply adding this file to that folder ensures the override is applied.
This is the only way that works for me in ExtJS 7.
Example:
app/desktop/overrides/Toast.js
Ext.define(null, {
override: 'Ext.window.Toast',
show : function () {
this.callParent();
// Your custom code here...
}
});

ExtJS4 - how to get parent grid on selectionchange?

I have little experience with ExtJS3 and now starting with version 4.
In my controller, I have this:
init: function ()
{
this.control({
"userlist":
{
selectionchange: function (view, selected, opts)
{
//get to grid??
}
}
});
}
How can I access the grid that this event happened on, without using id's?
I want to enable/disable buttons on the grid toolbar (tbar) if there are items selected, but I don't want to give anything id's (not the bar, not the individual buttons)
EDIT: the solution was to use the refs property in the controller:
refs:
[
{
ref: "list",
selector: "userlist"
}
],
selectionchange: this.activateTbButtons
activateTbButtons: function (selected, opts)
{
if (selected.selected.length == 1)
{
var tb = this.getList().query("toolbar");
}
}
Just found out that you can use the attribute view, and views under Ext.selection.Model.
This can be useful in cases when you let's say open multiple instances of your objects.
So, to access the grid in your example:
selectionchange: function (view, selected, opts) {
//get to grid??
var grid = view.view.ownerCt;
}
Having the same problem and found the previous answers missing some points. In short, I recommend:
selectionchange: function (selModel, selected, eOpts) {
var grid = selModel.view.ownerCt;
}
This was already proposed by Adezj although it referred to the selectionchange event that has the view as the first argument, and is not applicable to ExtJS 4.0.7+. (Don't think that selectionchange ever had the view as an argument?)
Note that this might not be officially supported by ExtJS since the view property of the selection model is not mentioned in the API docs at all.
Another approach is to use Ext.ComponentQuery.query(...) or defining refs in the controller, as proposed by Arun V, which is basically just a handy wrapper for Ext.ComponentQuery.query(). This works fine if you only have individual instances of the grid class but you need to take care in case you have multiple instances of the same grid class. Simply doing Ext.ComponentQuery.query('xtype-of-your-grid') will return all instances of your grid and you will have lots of fun finding out in which one the user has selected something.
So, in general, I would highly recommend to always work your way up from the component or object that fired the event to be sure you are in the right branch of the component hierarchy unless you are sure you will never have more than one instance of that class you write a controller for.
EDIT
I took a look at the docs for the selectionChange event:
selectionchange( Ext.selection.Model this, Ext.data.Model[] selected, Object eOpts )
The view is not being passed in to the selectionchange handler. An easy way to handle this is to either use Ext.getCmp() or use refs as seen in the docs for Ext.app.Controller:
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.app.Controller
//get grid
var grid = selectionModel.view.ownerCt.ownerCt;

Sencha Touch 2 button loose listener

I have a button in a Sencha Touch 2 project.
The button gets destroyed with the view after being pressed and is rebuild after another button gets pressed.
But the button does not get the listener again.
the listener is build in the controller of the view.
Ext.application({
name: 'App',
controllers: ['Main','Home'],
views: ['Main','Home'],
launch: function () {Ext.Viewport.add({xtype:'mainview'});}
});
the controller
Ext.define('App.controller.Home', {extend: 'Ext.app.Controller',
config: {
refs: {homeView: '#homeview',backBtn: '#btn_test1'},
control: {
backBtn: {
tap: function(backBtn){
console.log('[Controller][Home] btn monatsrate - - tap');
Ext.Viewport.add({xtype: 'mainview'});
Ext.Viewport.setActiveItem(1);
}
},
homeView: {
deactivate: function (homeView){
console.log('[Controller][Home] autodestroy homeview');
//homeView.destroy();
Ext.Viewport.remove(homeView);
}
}
}
},
});
And the view
Ext.define("App.view.Main", {
extend:"Ext.Container",
xtype:"mainview",
config:{
id:'mainview',
items:[
{
xtype:'button',
id:'btn_test2',
text: 'test2'
}
]
},
});
Any idea how to allow the button to get the listener back?
This is because the "ref" in your controller is using the id of the button to create the ref. Instead, use a different selector for your button. For example you could give your button a "name" property and give it a value of "testbutton". Then your ref would be like
refs: {homeView: '#homeview',backBtn: 'button[name=testbutton]'},
I struggled with this same problem for buttons and list items that were created/destroyed many times throughout the application's flow. Since then I've read a few times that, in general, the Sencha Touch team recommends not using the id as the selector unless you have a specific reason to. The "name" method above works very well for me. You could use lots of other css-style selectors as well (you'd have to read up on that separately).
As mentioned in a previous comment, I would accept some answers to increase the probability of getting an answer to your questions in the future. I'm just answering this one because I beat my head against the wall on this issue for 4 hours.
Sencha's examples recommend using action config on buttons, like 'cancel', 'goHome', 'createPost', etc.. which kinda makes sense.
All refs are then in the form of: myContainer button[action=myAction]
I believe your issue is exactly the id parameter. If you ever add any id you should make sure it is unique, thus adding an id to a config of your custom view will result in no way to create more then one instance of it! I may not be a 100% right(might be inside a container but i believe it will cause issues anyway) but why would you want an id that much? Besides, you can simply reference your view by xtype:
refs: {homeView: 'homeview',backBtn: 'btn_test1'},
regards,

how to create reusable and MCV-compatible form fields in extjs4?

I have some form fields and field sets and i want to reuse them in different views( Which may have different layouts and/or more fields).
I need a solution under which i dont have to repeat these form fields in every view i create and i want to reuse previously defined ones.What do you suggest for a MVC-based application?
Here is a very basic custom component that you can reuse in forms (it would go in your app/form/field folder with name InterestRate.js):
Ext.define('app.form.field.InterestRate', {
extend: 'Ext.form.field.Number',
alias:'widget.ratefield',
minValue:0,
step:0.05,
fieldLabel:'Rate'
});
You could then use it in a form like this:
Ext.define('app.view.Quote', {
extend:'Ext.form.Panel',
requires:[
'app.form.field.InterestRate'
],
items:[
{
xtype:'ratefield'
}
]
});
You can make the component as complex as you want, such as a whole grid or a fieldcontainer with multiple items.
The question is, do you want its behaviour to be self-contained, or to be controlled by the controller of the main form?

editorgrid as variable is not editable

In my application, I´m creating several modal windows which contains a form and an editorgrid. In order to re-use the components, I´ve created the combos, fieldtext, checkbox and other stuff as variables, and only add the necesarry to each window. One of those variables is an editorgrid, xtype: 'editorgrid', and there is the issue:
If I add the variable myEditorGrid to the panel, it works OK the first time I open the window, but the second time that any window has to render the same editorgrid, then the fields cannot be edited any more.
If I create the editorgrid inside the panel (and don´t use the variable), then it works OK everytime I open the window, but I need to copy&paste the same code over and over to all the windows, and that´s not very professional.
I thought the problem is that the variable is not destroyed, and made sure that the windows is closed, but I don´t know how to destroy the variable, and even if this is the solution.
Any idea?
Thanks
You can't reuse an EditorGrid in this manner, because it's column model gets destroyed after use.
The best way to reuse a component is to use the Ext.extend method described here, and then in your initComponent have something like..
initComponent : function() {
this.cm = new Ext.grid.ColumnModel({
columns: [
//define columns here
]
});
this.ds = new Ext.data.JsonStore({
//store config
});
//...
}

Resources