Add a auto initialize function inside a Sencha Touch model to manipulate model's data - sencha-touch-2

When I load a store, due to the API structure, I get a json object inside my model:
Ext.define('TestApp.model.SecretKeyModel', {
extend: 'Ext.data.Model',
config:{
identifier: {
type: 'uuid'
},
fields: [
{ name:'theRecord', type:'json' }
]
},
extractToken: function() {
var record = this;
var token = record.initSession.token;
console.log('token: ' + token);
}
});
I need to extract the token from that json object.
For that, i think I should write a function right there, inside the model.
How can I call it, when the store loads, to manipulate the data and extract the token?

I faced a similar situation 1 hour ago, i needed to edit data during loading or immidiatly after. I ended with this solution:
Ext.define('TestApp.store.MyStore', {
extend: 'Ext.data.Store',
requires: ['TestApp.model.SecretKeyModel'],
config :{
model: 'TestApp.model.SecretKeyModel',
proxy: {
type: 'ajax',
url: TestApp.utils.GlobalVariables.getServerUrl(),
reader: {
type: 'json',
rootProperty: ''
}
},
listeners: {
refresh: function(store, data, eOpts) {
store.each(function (item, index, length) {
item.extractToken(); // call this on every record loaded in the store
});
}
}
}
});

Related

YQL in sencha touch MVC

I am looking for some blog or example for YQL explaining with MVC architecture. I feel difficult in understanding kitchen sink example. Can any one share simple MVC on YQL. so it will be helpful for other also.
I don't know about YQL, but based on the link user3849047 provided it's basically a request against some remote api. So integration might be a little bit more tricky than in this draft.
Basically, this is how it should work.
You will get some kind of data from the api calls. This data can be represented as an Ext.data.Model. A bunch of models is organized and stored in Ext.data.Store.
So all you have to do is populating the store somehow.
There are two ways.
Do it in your controller:
Ext.create("Controller", {
extend: "Ext.app.Controller",
getStoreData: function () {
var me = this;
Ext.data.JsonP.request({
url: "yqlRequestUrl",
params: {
// request parameter
},
success: function ( result, request ) {
me.fillStore( result );
}
});
},
fillStore: function ( result ) {
var data = transformResultIntoModels( result );
var store = Ext.getStore("myStore");
store.add( data );
}
});
You execute the api request and the transformation of the response into the models all by yourself.
Or let your store do it for you:
Ext.define("MyStore", {
extend: "Ext.data.Store",
autoLoad: false,
storeId: "mystore",
model: "MyModel",
proxy: {
type: "jsonP",
url: "yqlRequestUrl",
extraParams: {
// request parameter
},
reader: {
type: "json",
rootProperty: "yourRootElement"
}
}
});
Since this store is set to autoLoad: false you have to load the store manually by
store.load({
callback: function ( records, operation, success ) {
},
scope: this
});

How to configure a Sencha Touch 2 store, to read a multiple level json object

I need to connect to an API using a Sencha Touch store and a mode.
The problem represents the API's response json, which is similar to:
{
"The_Api": {
"initSession":{
"calledMethod":"The_Api::initSession",
"status":"1",
"error":"0",
"errorCode":"0",
"errorMessage":"",
"data":{
"token":"api_535f6c5d68dc78.56464399"
}
}
}
}
I need to retrieve the token value from this response.
How to I configure my store to get to the token value?
Ext.define('TestApp.store.SecretKeyStore', {
extend: "Ext.data.Store",
config: {
storeId: 'SecretKeyStore',
model: "TestApp.model.SecretKeyModel",
params: {
lang: 'FR',
method: 'initSession',
username: TestApp.utils.GlobalVariables.getUsername(),
secretKey: TestApp.utils.GlobalVariables.getSecretKey()
},
proxy: {
type: 'ajax',
noCache: true,
url: '/rest_json.php',
remoteFilter:true,
reader: {
type: 'json',
rootProperty: 'data'
}
}
}
});
What root property should I use?
Its a js object so this should work:
rootProperty:'The_Api.initSession.data'

Update record in Sencha Touch Data Store with Ajaxproxy

I'm developing a simple form with Secha Touch. I have defined a DataStore for my model like this:
App.stores.shopinglists = new Ext.data.Store({
model: 'ShopingList',
autoLoad: false,
proxy: new Ext.data.AjaxProxy({
type: 'ajax',
url: 'http://localhost:2795/ShopingListService/',
reader: {
type: 'json',
root: 'ResultData',
totalProperty: 'Total',
successProperty: 'Success'
},
writer: {
encode: true,
type: 'json'
}
})
});
The view loads fine, and I can see a list of items and edit them. However, when I click the update button, I get the following error:
Uncaught Error: You are using a ServerProxy but have not supplied it with a url.
What I am missing here? The proxy has the url defined, but when update is invoked, it's undefined.
Edit: The button just call a controller action.
onSaveAction: function () {
var model = this.getRecord();
Ext.dispatch({
controller: 'ShopingLists',
action: (model.phantom ? 'save' : 'update'),
data: this.getValues(),
record: model,
form: this
});
},
The code executed by the controller is this:
update: function (params) {
debugger;
var tmpshopingList = new App.models.ShopingList(params.data);
var errors = tmpshopingList.validate();
if (errors.isValid()) {
params.record.set(params.data);
params.record.save();
this.index();
} else {
params.form.showErrors(errors);
}
},
I think I know what is happening: The model knows it has a server proxy, but all of the configurations are not being copied over. Perhaps this is a bug with Sencha Touch 1.x.
Try putting the proxy configuration into your model, not your store.

ExtJS: How do I get raw JSON data from Ext.data.Store?

From a typical store like this
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{name: 'firstName', type: 'string'},
{name: 'lastName', type: 'string'},
{name: 'age', type: 'int'},
{name: 'eyeColor', type: 'string'}
]
});
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'ajax',
url : '/users.json',
reader: {
type: 'json',
root: 'users'
}
},
autoLoad: true
});
Is it possible to get raw Json from myStore?
What about:
myStore.proxy.reader.rawData
The accepted solution did not work in my configuration: ExtJs 4.1 and a grid with a memory proxy - it returned empty after I added items to the gird (and the store object reflected that). The following code worked for encoding store contents into a JSON string:
var json = Ext.encode(Ext.pluck(store.data.items, 'data'));
Cheers!
Took me ages to find a solution to this but here is one solution that will work.
myStore .on({ 'load': function (store, records, successful)
{
console.log(store.getProxy().getReader().rawData);
}
});
The proxy reader rawData/jsonData will become accessible after the store is created. To access it try the following:
store.on('load', function() {
console.log('store.proxy.reader.jsonData');
console.log(store.proxy.reader.jsonData);
}, this, { single: true });
Ext.data.Store({....
proxy: {
...
reader: {
**keepRawData: true,**
type: 'json',
rootProperty: 'root',
successProperty: 'success'
}
}
});
Look like I found the solution by hooking event listeners to data store:
var myStore = Ext.create('Ext.data.Store', {
...
listeners: {
'load': {
fn: function(store, records, success, operations) {
Ext.each(records, function(rec) {
console.log(Ext.encode(rec.raw));
});
}
}
}
...
});
maybe, you can try with this:
var json = Ext.JSON.encode(myStore.getRange());
cya!

Sencha-touch : refresh list : store

I have a list of news in a Ext.List inside a panel
prj.views.NewsList = Ext.extend(Ext.Panel, {
layout: 'card',
initComponent: function() {
this.list = new Ext.List({
itemTpl: '......',
loadingText: false,
store: new Ext.data.Store({
model: 'News',
autoLoad: true,
proxy: {
type: 'ajax',
url: '.....',
reader: {
type: 'json',
//root: ''
}
},
listeners: {
load: { fn: this.initializeData, scope: this }
}
})
});
this.list.on('render', function(){
this.list.store.load();
this.list.el.mask('<span class="top"></span><span class="right"></span><span class="bottom"></span><span class="left"></span>', 'x-spinner', false);
}, this);
this.listpanel = new Ext.Panel({
items: this.list,
layout: 'fit',
listeners: {
activate: { fn: function(){
this.list.getSelectionModel().deselectAll();
Ext.repaint();
}, scope: this }
}
})
this.items = this.listpanel;
prj.views.NewsList.superclass.initComponent.call(this);
},
});
Ext.reg('newsList', prj.views.NewsList);
In a toolbar setup in a dockedItem, I have a icon to refresh the list.
items: [
{
iconCls: 'refresh',
handler: function() {
prj.view.NewsList.list.store.read()
}
},
]
but prj.view.NewsList return undefined! How can I get the list to do a refresh of the store?
Call this line on your refresh button
Ext.StoreMgr.get('newsStore').load()
The list is automaticaly refresh when you call the load() method on the store. The store is linked to the list.
Example:
items: [
{
iconCls: 'refresh',
handler: function(event, btn) {
Ext.StoreMgr.get('newsStore').load();
}
},
]
Even I faced a similar problem.
I am posting my answer hope this helps someone.
I have a search bar in to search data. (my search is taking place at server and the results are sent back to me in response to my GET request.
Basically I just had to change the URL for my store
WHAT ALL I TRIED:
myList.refresh(),
myStore.load();
clearing the store and then loading it
removing the list and adding it again and forcing it to re render (using doLayout())
Nothing worked...
just adding SINGLE line fixed my problem
function handleSearch(strSearchText)
{
//myStore.loadData([],false); /tried to clear the store and reloading it
if(strSearchText !='')
{
searchString = '?search='+strSearchText;
searchURL = searchURLBasic+ searchString;
}else{
searchURL = searchURLBasic;
}
console.log('search URL: ' + searchURL);
myStore.proxy.url =searchURL; // this was one magical line of code that saved my life
myStore.load();
}
THanks SO for support.
I do this when changing the store and it works like a champ
var yourbutton = new Ext.Panel({
listeners: {
afterrender: function(c){
c.el.on('click', function(){
YourList.update();
YourList.bindStore(newStore);
});
}
}
});