Ext.bind Does Not See Function In ExtJS
Solution 1:
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).
Post a Comment for "Ext.bind Does Not See Function In ExtJS"