Freitag, 2. März 2012

Overwrite RestProxy in Sencha Touch 2

Here are the steps how you can override Sencha Touch functionalities. In this simple case I override the buildUrl method in Ext.data.proxy.Rest to customize the URL for my needs. Create a new class. There is no naming convention although I think it is useful to use the naming scheme from the class you are overriding. So in my case I'm using MyApp.data.proxy.CustomRestProxy. Instead of extend you'll then have to use override to specify the class whose functionality you want override.

Ext.define('MyApp.data.proxy.CustomRestProxy', {
 override: 'Ext.data.proxy.Rest',
 
   buildUrl: function(request) {
     //here I simply add an url prefix to all rest calls
         var  me = this, _serviceUrl = globalConf.serviceUrl, url = me.getUrl(request);
         request.setUrl(_serviceUrl + url);

         return me.callParent([request]);
     }
});
Put this class in a folder according to the name.
Mine is located in app/data/proxy/CustomRestProxy.js

 In your app.js make sure to set this class as required.
requires: ['MyApp.data.proxy.CustomRestProxy'] 


When you start your App and Sencha complains it can't find your new class you have to tell Sencha where to look.

Put
Ext.Loader.setPath('MyApp', 'app'); 
Before you call
Ext.application ...

2 Kommentare:

  1. Thanks, so far, so good.
    But I'm getting problems using this proxy in a store config:

    Ext.define('JMA.store.MainStore', {
    extend: 'Ext.data.Store',
    config: {
    ...
    proxy: {
    type: 'JMA.data.proxy.WebApiRest',
    }
    }
    }

    yields

    "Uncaught Error: [Ext.createByAlias] Cannot create an instance of unrecognized alias: proxy.JMA.data.proxy.WebApiRest"

    and
    Ext.define('JMA.store.MainStore', {
    extend: 'Ext.data.Store',
    config: {
    ...
    proxy: {
    type: 'WebApiRest',
    }
    }
    }

    yields
    "Uncaught Error: [Ext.createByAlias] Cannot create an instance of unrecognized alias: proxy.WebApiRest"

    AntwortenLöschen
  2. Hi there,

    in my example I'm using an override so it is used automatically.
    --> override: 'Ext.data.proxy.Rest',

    Instead of an override you can use an extend.
    In this case something like this should work:

    proxy: new JMA.data.proxy.WebApiRest({
    type: 'rest',
    //rest of the config for this proxy ...
    })

    AntwortenLöschen