Как встроить NestedList в TabPanel? - PullRequest
4 голосов
/ 14 марта 2012

Я пытаюсь создать представление tabpanel, которое содержит контроллер splitview на первой вкладке. Подумайте о демонстрации "кухонная раковина", размещенной в одной вкладке панели.

Остальные не содержат вложенный список.

http://dev.sencha.com/deploy/touch/examples/production/kitchensink/

enter image description here

Я попытался поместить nestedlist в контейнер, что вы можете увидеть в некоторых комментариях, приведенных ниже.

На данный момент этот рабочий код показывает только список гнезд, занимающий весь раздел на первой вкладке:

Ext.application({
    name: 'Test',

    requires: [
        'Ext.dataview.NestedList',
        'Ext.navigation.Bar'
    ],

    launch: function() {
        Ext.create("Ext.TabPanel", {
            fullscreen: true,
            tabBarPosition: 'bottom',
            items: [{
                id: 'tab4',
                title: 'Tab4',
                iconCls: 'star',
                xtype: 'container',
                items: [{
                    xtype: 'nestedlist',
                    displayField: 'text',
                    docked: 'left',
                    store: store
                }, {
                    html: 'Detail View'
                }]
            }, {
                id: 'tab2',
                title: 'Tab2',
                iconCls: 'star',

                html: 'No nav bar?'
            }, {
                id: 'tab3',
                title: 'Tab3',
                iconCls: 'star',

                html: 'Screen3'
            }]
        }).setActiveItem(0);
    }
});

Настройка магазина:

Ext.Loader.setConfig({ enabled: true });

var data = {
  text: 'Groceries',
  items: [{
    text: 'Drinks',
    items: [{
      text: 'Water',
      items: [{
        text: 'Sparkling',
        leaf: true
      },{
        text: 'Still',
        leaf: true
      }]
    },{
      text: 'Coffee',
      leaf: true
    },{
      text: 'Espresso',
      leaf: true
    },{
      text: 'Redbull',
      leaf: true
    },{
      text: 'Coke',
      leaf: true
    },{
      text: 'Diet Coke',
      leaf: true
    }]
  },{
    text: 'Fruit',
    items: [{
      text: 'Bananas',
      leaf: true
    },{
      text: 'Lemon',
      leaf: true
    }]
  },{
    text: 'Snacks',
    items: [{
      text: 'Nuts',
      leaf: true
    },{
      text: 'Pretzels',
      leaf: true
    }, {
      text: 'Wasabi Peas',
      leaf: true
    }]
  }
]};

Ext.define('ListItem', {
    extend: 'Ext.data.Model',
    config: {
        fields: [{
                name: 'text',
                type: 'string'
        }]
    }
});

var store = Ext.create('Ext.data.TreeStore', {
    model: 'ListItem',
    defaultRootProperty: 'items',
    root: data
});

1 Ответ

4 голосов
/ 23 марта 2012

Хорошо.Я создал этот пример для вас: http://www.senchafiddle.com/#ynn40

Вы также можете скачать весь исходный код отсюда: http://rwd.me/FG5s (достаточно большой, поскольку он включает SDK)

Убедитесь, чточтобы просмотреть все файлы, я добавил много документации.

Некоторые примечания:

  1. Я создал новый компонент с именем Sencha.view.SplitView.Это очевидно можно назвать чем угодно.Он имеет тип x splitview, поэтому мы можем просто потребовать его и включить в наш файл Main.js (который является Ext.tab.Panel.

    {
        xtype: 'splitview',
        title: 'SplitView',
        store: 'Items'
    }
    

    , поскольку это элемент внутри tabPanel,нам нужно также указать для него конфигурацию title. Конечно, мы можем включить этот компонент Splitview где угодно.

  2. Как вы можете видеть, он имеет конфигурацию store, определенную в SplitView.:

    config: {
        /**
         * We create a custom config called store here so we can pass the store from this component
         * (SplitView) down into the nested list when it updates. Checkout {@link #updateStore}
         * @type {Ext.data.Store}
         */
        store: null
    }
    

    Используется для передачи хранилища из splitview во вложенный список (мы вернемся к этому через секунду). Конечно, эта конфигурация ничего не изменит, если мы не добавим соответствующие методы для обновлениявложенный список:

    /**
     * This is called when the {@link #store} config has been updated.
     * We simply check if the nested list has been created, and if it has, set the store
     * on it with the new value.
     */
    updateStore: function(newStore) {
        if (this.nestedList) {
            this.nestedList.setStore(newStore);
        }
    }
    

    Как видите, мы просто обновляем хранилище nestedList (если оно существует) новым значением хранилища SplitView.

  3. Внутри initialize метода SplitView мы создали detailContainer (куда должна идти подробная карта вложенного списка) и nestedList, а затем добавили их в SplitView. Убедитесь, что вы посмотрите на некоторыеиз конфигураций, которыемы даем nestedList, поскольку они важны.Конфигурация магазина:

    // Set the store of this nested list to the store config of this component (Splitview)
    store: this.getStore()
    

    Конфигурации detailCard и detailContainer:

    // Tell the nested list to have a detail card and put it inside our new detailContinaer
    detailCard: true,
    detailContainer: this.detailContainer
    

    И, конечно, слушатели, чтобы мы знали, когда что-то изменится:

    // And finally add a listener so we know when to update the detail card
    listeners: {
        scope: this,
        leafitemtap: this.onLeafItemTap
    }
    
  4. Наконец, мы добавляем в Splitview метод onLeadItemTap (мы добавили слушателя выше), который должен обновить карточку сведений с новой информацией:

    /**
     * This is called when a leaf item is tapped in the nested list, or when the detail card
     * should be updated. In here, we just get the record which was tapped and then set the HTML
     * of the detail card.
     */
    onLeafItemTap: function(nestedList, list, index, node, record, e) {
        var detailCard = nestedList.getDetailCard();
        detailCard.setHtml(record.get('text'));
    }
    

Надеюсь, это имеет смысл и поможет вам.Если нет, дайте мне знать.

...