Как добавить собственное обновление при обновлении по запросу?

В стандартном плагине "Pull to Refresh" хранилище списка обновляется. Однако у меня есть два списка, и мне нужно обновить другой магазин для моего подробного списка. Как я могу переопределить событие обновления и перезагрузить другой магазин? Я пытался добавить простой слушатель, но он не стреляет.

[Обновить]

Я получил этот фрагмент с сайта Sencha для работы:

плагины: [
          {
             xclass: "Ext.plugin.PullRefresh",
              pullRefreshText: "Потяните вниз для новых событий!",
              refreshFn: function(плагин) {
                  console.log( "Я вытащил");
              }
           }
          ]

Оригинальный код:

Ext.define ('SenchaFiddle.view.ListView', {
    расширение: 'Ext.dataview.List',
    xtype: 'main-list',

    config: {
        плагины: [
            'Pullrefresh',
            {
                pullRefreshText: "Сделай это!",
                тип: 'listpaging',
                // Не предлагать сообщение "Загрузить больше"
                AutoPaging: ложь,

                 refreshFn: function () {              
                   console.log ("Стрела"); 
                 }, 

                 слушатели: { 
                     'updatedata': функция (плагин, список) { 
                         console.log ("Получение данных"); 
                     } 
                 } 

            }
        ],
        макет: "подходит",
        ширина: 300,
        itemTpl: '{text}'

    }
});

3 ответа

Решение

Глядя на Ext.plugin.PullRefresh определение в sencha-touch-all-debug, я вижу этот конфиг:

    /*
     * @cfg {Function} refreshFn The function that will be called to refresh the list.
     * If this is not defined, the store's load function will be called.
     * The refresh function gets called with a reference to this plugin instance.
     * @accessor
     */
    refreshFn: null,

Это может быть хорошей идеей, что вы можете достичь того, что вам нужно с помощью refreshFn конфигурации.

В Sencha Touch 2.2 они удалили refreshFn конфиг из Ext.util.PullRefresh. Я успешно реализовал кастом refreshFn с новой версией Sencha Touch, переопределив fetchLatest функция внутри Ext.util.PullRefresh вот так...

Ext.define('MyApp.overrides.PullRefreshOverride', {
    override: 'Ext.plugin.PullRefresh',

    fetchLatest: function() {
        var list = this.getList();

        switch(list.getItemId()) {
            case "list1": 
                this.updateStore1();
                break;

            case "list2": 
                this.updateStore2();
                break;
        }

        this.callParent(arguments);
    },

    //My own custom function to add to the plugin
    updateStore1: function() {
        //Code to update store 1
    },

    //My own custom function to add to the plugin
    updateStore2: function {
        //Code to update store 2
    }
});

Для тех, кому нужно refreshFn назад, есть расширение PullRefreshFn для PullRefresh,

Мне нужно было, чтобы PullRefresh запускался Panel, а не списком или Dataview, и мне также нужно было вручную загружать и устанавливать данные в мой Dataview при запуске пользователем PullRefresh.

Для этого мне понадобился refreshFn Функция config, существовавшая до Sencha 2.2, так что здесь моя реализация.


PullRefreshFn (изменено)

Ext.define('Ext.plugin.PullRefreshFn', {
    extend: 'Ext.plugin.PullRefresh',
    alias: 'plugin.pullrefreshfn',
    requires: ['Ext.DateExtras'],

    config: {
        /**
         * @cfg {Function} refreshFn The function that will be called to refresh the list.
         * If this is not defined, the store's load function will be called.
         */
        refreshFn: null
    },

    fetchLatest: function() {
        if (this.getRefreshFn()) {
            this.getRefreshFn().call();
        } else {
            var store = this.getList().getStore(),
                proxy = store.getProxy(),
                operation;

            operation = Ext.create('Ext.data.Operation', {
                page: 1,
                start: 0,
                model: store.getModel(),
                limit: store.getPageSize(),
                action: 'read',
                sorters: store.getSorters(),
                filters: store.getRemoteFilter() ? store.getFilters() : []
            });

            proxy.read(operation, this.onLatestFetched, this);
        }
    }

});

Мой контроллер

Ext.define('myApp.controller.MyController', {
    extend: 'Ext.app.Controller',
    requires: ['Ext.plugin.PullRefreshFn'],

    ...

    // More code

    ...

    // Binds the Pull Refresh to myPanel view item.
    // myPanel is a panel. Not list nor dataview.
    setPullRefresh: function () {
        var me = this;

        // We get reference to myPanel and
        // we set PullRefreshFn
        this.getMyPanel().setPlugins([{
            xclass: 'Ext.plugin.PullRefreshFn',
            docked: 'top',

            // We set autoSnapBack to false,
            // as we are going to trigger this manually
            autoSnapBack: false,

            // refreshFn will be called upon user releasing for refresh.
            refreshFn: function() {

                // This is a custom function that sets data to our dataview list.
                // When it's done setting data, we trigger the snapBack.
                me.populateMylist(function () {
                    me.getMyPanel().getPlugins()[0].snapBack(true);
                });
            }
        }]);
    }

});
Другие вопросы по тегам