Reputation: 1855
I'm using ExtJS 4 and abiding by their MVC pattern. I'm a little confused on where to put helper functions used by event handlers. This is currently what I'm doing:
Ext.define('App.controller.myController, {
extend: 'Ext.app.Controller.
stores: [...],
models: [...],
views: [...],
init: function() {
this.control({
'selector' : {
event1: this.onEvent1,
event2: this.onEvent2
}
});
},
onEvent1: function(args) {
// do stuff
helperFn();
},
onEvent2: function(args) {
// do other stuff
helperFn();
}
});
// is this 'right'?
function helperFn() {
// do other, other stuff
}
Is this the correct setup? Or should I do something like:
Ext.define('App.controller.myController, {
extend: 'Ext.app.Controller.
stores: [...],
models: [...],
views: [...],
init: function() {
this.control({
'selector' : {
event1: this.onEvent1.bind(this),
event2: this.onEvent2.bind(this)
}
});
},
onEvent1: function(args) {
// do stuff
this.helperFn();
},
onEvent2: function(args) {
// do other stuff
this.helperFn();
},
helperFn(): function() {
// do other, other stuff
}
});
Is one style preferred? I.e. are there any major drawbacks of either one compared to the other?
Upvotes: 0
Views: 689
Reputation: 1562
By defining your helper function outside of the controller's definition, you're making it a global function. This means that the function will be available everywhere in your application. If this is a requirement, I would define a separate utility singleton which contains helperFn
.
//in a separate file...
Ext.define('App.Util', {
singleton: true,
helperFn: function() {
// do other, other stuff
}
});
Ext.define('App.controller.myController, {
extend: 'Ext.app.Controller.
stores: [...],
models: [...],
views: [...],
init: function() {
this.control({
'selector' : {
event1: this.onEvent1.bind(this),
event2: this.onEvent2.bind(this)
}
});
},
onEvent1: function(args) {
// do stuff
App.Util.helperFn();
},
onEvent2: function(args) {
// do other stuff
App.Util.helperFn();
}
});
By defining it inside the controller's definition, you're making it a member of the controller class. This means that it can be called by the instance of the controller only. This is generally preferred if the code is specific to the controller.
There is a third option available. If you want the function to be available only within the controller, but not accessible to anything else (similar to a private method in Java), you can set it up like this:
Ext.define('App.controller.myController', (function () {
//now the function is only available below through closure
function helperFn() {
// do other, other stuff
}
return {
extend: 'Ext.app.Controller',
stores: [...],
models: [...],
views: [...],
init: function () {
this.control({
'
selector ': {
event1: this.onEvent1.bind(this),
event2: this.onEvent2.bind(this)
}
});
},
onEvent1: function (args) {
// do stuff
helperFn();
},
onEvent2: function (args) {
// do other stuff
helperFn();
}
};
})());
Upvotes: 4