Ok so you set out to code your new extjs app using MVC and now you want to do something like add a ‘datachanged’ or ‘load’ event to your store. This is common stuff right, you know exception handlers, so you open up Google or stack overflow and start searching, but what you get is a whole lot of differing opinion on how to accomplish this trivial task. There are a few things that you already know; they are your ground rules so to say. Come hell or high water you will not add listeners to your store, you want all of the methods (or actions) to go in the controller. So what are you to do?
First let’s look at our sample store:
Ext.define('sample.store.MainStore', {
extend : 'Ext.data.Store',
model : 'sample.model.MainStore',
pageSize : 100,
remoteSort : true,
proxy: {
type: 'ajax',
extraParams: {
start : 0,
limit : 100
},
url: 'someurl.php',
method: 'POST',
reader: {
type: 'json',
root: 'data',
totalProperty:'results'
}
},
autoLoad: true
});
… and every store has a model, right …
Ext.define('sample.model.MainStore', {
extend: 'Ext.data.Model',
fields: [
'some_primary_key',
'some_data_element',
]
});
Now for the Pièce de résistance – our controller:
Ext.define('sample.controller.Main', {
extend : 'Ext.app.Controller',
models : ['MainStore'],
stores : [' MainStore '],
views : ['Main'],
requires : ['Ext.MessageBox'],
init: function() {
Ext.getStore('MainStore').addListener('load',
this.onMainStoreLoad,
this);
Ext.getStore('MainStore').addListener('datachanged',
this. onMainStoreDataChange,
this);
this.control({
// A sample combo box select function
'combo[action=sampleSelect]':{
select:this.onComboSelect
},
// A sample button click function
'button[action=sampleAction]':{
click:this.onButtonClick
}
});
},
// This is where all the functions go
onComboSelect: function(combo) {
console.log('ComboBox Selected, the value is:' + combo.getValue()) ;
},
onButtonClick: function(me){
console.log('Button Clicked');
},
onMainStoreLoad: function(me,records,success){
if(!success){
Ext.MessageBox.show({
title : 'Data Load Error',
msg : 'The data encountered a load error, please try again in a few minutes.'
});
}
},
onMainStoreDataChange: function(me){
console.log('Hey the store data just changed!');
}
});
In closing there are a few things that I learned in this exercise that I would like to point out so you don’t repeat my mistakes.
- When you look at the API for the store, and you take one of the events (load for example is here http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Store-event-load ) you can pass the parameters in the function in the controller.