3

Я хочу, чтобы выполнить операцию выбора на Списокпосле того, как данные были загружены, потому что на основе данных, которые я получил, я должен выбрать одну ячейку в этом списке, а также необходимо обновить базу данных подробностей.Добавить OnLoad Слушатель в Сенча Список сенсорный

Ext.define('WaxiApp.view.ProductViews.ProductList', { 
    extend: 'Ext.Container', 
    alias: "widget.ProductList", 
    requires: [ 
        'Ext.Img', 
    ], 
    config: { 
     layout: Ext.os.deviceType == 'Phone' ? 'fit' : { 
      type: 'hbox', 
      pack:'strech' 
     }, 
     cls: 'product-list', 
     items: [{ 
      xtype: 'list', 
      id:'product-list-view', 
      width: '100%', 
      height:'100%', 
      store: 'ProductsList', 
      infinite: true, 
      plugins: 'sortablelist', 
      itemCls: 'productList', 
      itemId:"product-item", 
      itemTpl: new Ext.XTemplate(
       '<div class="list-content-div ', 
     '<tpl if="this.needSortable(isNeedInventry)">', 
      Ext.baseCSSPrefix + 'list-sortablehandle', 

     '</tpl>', 
     '">', 
     '<b>{UpcCode} {Name}</b>', 
     '<tpl if="isActive">', 
      '</div>', 
     '</tpl>', 
      { 
       // XTemplate configuration: 
       compiled: true, 
       // member functions: 
       needSortable: function (isneedInventry) { 
        return !isneedInventry; 
       }, 
      }), 
      masked: { xtype: 'loadmask',message: 'loading' }, 
      onLoad: function (store) { 
       this.unmask(); 
       console.log('list loaded'); 
       this.fireEvent("productListLoadedCommand", this,store); 
      }, 

     } 
     ], 
     listeners: [ 
       { 
        delegate: "#product-list-view", 
        event: "itemtap", 
        fn: function (list, index, target, record) { 
         console.log(index); 
         console.log('list selection command fired'); 
         this.fireEvent("productListSelectedCommand", this,index,record); 
        } 
       } 

     ], 
     style: 'background-image: -webkit-gradient(linear, left top, right bottom, color-stop(0, #FDFDFD), color-stop(1, #DBDBDB));background-image: linear-gradient(to bottom right, #FDFDFD 0%, #DBDBDB 100%);' 
    }//End of config 

});//End of Define 

Над этим фактическим видом я использовал для отображения списка. Моя проблема в том, что я попытался использовать метод onLoad(), но я хочу сделать все в моем контроллере, чтобы сделать его более понятным.

Как вы видели, мое событие itemTap было обработано в Контроллере, активировав событие. Но то же самое не работает для события load.

ответ

0

Я нашел решение, как справиться с этим сценарием, и разместил мое собственное решение .

ProductList.js

Ext.define('WaxiApp.view.ProductViews.ProductList', { 
extend: 'Ext.Container', 
alias: "widget.ProductList", 
requires: [ 
       'Ext.Img', 
], 
initialize: function() { 

    this.add([ 
     { 
      xtype: 'list', 
      id: 'product-list-view', 
      store: 'ProductsList', 
      masked: { xtype: 'loadmask', message: 'loading' }, 
      //onLoad is not a listener it's private sencha touch method used to unmask the screen after the store loaded 
      onLoad: function (store) { 
       this.unmask();//I manually unmask, because I override this method to do additional task. 
       console.log('list loaded'); 
       this.fireEvent("productListLoadedCommand", this, store); 
      } 
      , 
      //Painted is event so added it to listener, I saw fee document state that, add event like Painted and show should to added to the 
      //Component itslef is best practice. 
      listeners: { 
       order: 'after', 
       painted: function() { 
        console.log("Painted Event"); 
        this.fireEvent("ProductListPaintedCommand", this); 
       }, 
       scope: this 
       //This is also very important, because if we using this in card layout 
       //and changing the active view in layout cause this event to failed, so 
       //setting scope to this will help to receive the defined view instead of this list component. 
      } 

     }]); 
}, 

config: { 
    listeners: [ 
      { 
       delegate: "#product-list-view", 
       event: "itemtap", 
       fn: function (list, index, target, record) { 
        console.log(index); 
        console.log('list selection command fired'); 
        this.fireEvent("productListSelectedCommand", this, index, record); 
       } 
      } 
    ], 

    }//End of config 

});//End of Define 

ProductViewController.js

/// <reference path="../../touch/sencha-touch-all-debug.js" /> 


Ext.define("WaxiApp.controller.ProductsViewController", { 

    extend: "Ext.app.Controller", 
    listStoreNeedLoad:true, 
    config: { 
     refs: { 
      ProductContainer: "ProductList", 
      ProductList: "#product-list-view", 
      ProductDetailView:"ProductDetail" 
     }, 
     control: { 
      ProductContainer:{ 
       productListSelectedCommand: "onProductListSelected", 
       ProductListPaintedCommand: "onProductListPainted" 
      }, 
      ProductList:{ 
       productListLoadedCommand: "onProductListLoaded"   
      } 

     }//End of control 

    },//End of config 
    // Transitions 
    getstore:function(){ 
     return Ext.ComponentQuery.query('#product-list-view')[0].getStore(); 
    }, 
    onProductListPainted:function(list) 
    { 
     //Check for if need to load store because painted event called every time your view is painted on screen 
     if (this.listStoreNeedLoad) { 
      var store = this.getstore(); 
      this.getstore().load(); 
     } 
    }, 
    onProductListLoaded:function(list,store) 
    { 
     this.listStoreNeedLoad = false; 
     var index = 0; 
     //Iterate through record and set my select Index 
     store.each(function(record,recordid){ 
      console.info(record.get("isNeedInventry")); 
      if (record.get("isNeedInventry")) { 
       return false; 
      } 
      index++; 
     }); 

     console.log('list load event fired'); 
     if(Ext.os.deviceType.toLowerCase()!='phone') 
     { 
      this.setRecord(store.getAt(index)); 
      list.select(index); 
     } 

    } 

})//End of define 
0

В документации к Sencha Touch я не вижу функцию onLoad для Ext.dataview.List. Тем не менее, есть load прослушиватель событий для Ext.data.Store, который содержит список. Таким образом, ваш слушатель событий должен, вероятно, находиться в хранилище данных, а не обязательно сам список.

Внутри метода запуска вашего контроллера, вы могли настроить слушатель для события загрузки магазина следующим образом:

launch: function() {   
    // your store should be setup in your Ext.application 
    Ext.getStore('NameOfStore').on('load', this.productListLoadedCommand); 
}, 

productListLoadedCommand: function(store, records, successful, operation, eOpts) { 
    // do some after load logic 
} 

Вы должны настроить слушатель событий для вашего списка в контроллере, а также. Вам не нужно будет создавать слушателя в конфигурации просмотра только для вызова метода fireEvent в контроллере. Вместо этого выполните всю обработку событий в контроллере. Чтобы получить ручку в своем списке в контроллере, добавьте xtype: 'productlist' внутри Ext.define для вашего WaxiApp.view.ProductViews.ProductList. Затем добавьте свой список конфигурации Контролера как иая и прикрепить itemtap события для списка в элементе управления следующим образом:

config: { 
    ref: { 
     productList: 'productlist' 
    }, 

    control: { 
     productList: { 
      itemtap: 'productListSelectCommand' 
     } 
    } 
}, 

productListSelectCommand: function (list, index, target, record, e, eOpts) { 
    // do some itemtap functionality 
} 

В конце концов, ваш контроллер может выглядеть примерно так:

Ext.define('MyApp.controller.Controller', { 
    extend: 'Ext.app.Controller', 

    requires: [ 
     // what is required 
    ], 

    config: { 
     ref: { 
      productList: 'productlist' 
     }, 

     control: { 
      productList: { 
       itemtap: 'productListSelectCommand' 
      } 
     } 
    }, 

    launch: function() {   
     // your store should be setup in your Ext.application 
     Ext.getStore('NameOfStore').on('load', this.productListLoadedCommand); 
    }, 

    productListLoadedCommand: function(store, records, successful, operation, eOpts) { 
     // do some after load logic 
     // this.getProductList() will give you handle of productlist 
    }, 

    productListSelectCommand: function (list, index, target, record, e, eOpts) { 
     // do some itemtap functionality 
    } 
} 

Наконец, не забудьте добавить xtype: 'productlist' внутри Ext.define для вашего WaxiApp.view.ProductViews.ProductList. Я не уверен в вашем общем опыте разработки приложений Sencha Touch, но here - хорошая ссылка для понимания их вида, модели, магазина, структуры контроллера.

+0

Предложение Каус ур метод может работать, но проблема. с таким подходом, когда представление уничтожается и воссоздание контроллера не будет обрабатывать события itemtap, назначенные через контроллер. также я нашел способ использовать ** метод onLoad() для компонента ** для достижения моей задачи. – CoolMonster

2

Как указано @Jimmy, нет onLoad метод в списке. Однако есть несколько способов обойти это. Мое понимание того, что вы хотите достичь, заключается в том, что при загрузке хранилища в список вы хотите, чтобы событие запускалось из экземпляра ProductList (а не list), так что в контроллере вы можете настроить control следующим образом:

control: { 
    ProductList: { 
     productListSelectedCommand: 'productListSelectCommand', 
     productListLoadedCommand: 'productListLoadedCommand' 
    } 
} 

Если так, то мы можем изменить слушателей в существующем ProductList классе сделать следующее:

listeners: [ 
    { 
     delegate: "#product-list-view", 
     event: "itemtap", 
     fn: function (list, index, target, record) { 
      console.log(index); 
      console.log('list selection command fired'); 
      this.fireEvent("productListSelectedCommand", this,index,record); 
     } 
    }, 
    { 
     delegate: "#product-list-view", 
     event: "show", 
     fn: function (list) { 
      var store = list.getStore(); 
      var handler = function() { 
       list.unmask(); 
       console.log('list loaded'); 
       this.fireEvent("productListLoadedCommand", this, store); 
      }; 
      if (store.isLoaded()) { 
       handler.apply(this) 
      } else { 
       list.getStore().on('load', handler, this); 
      } 
     } 
    } 
] 

Что это делает это к тому, что в списке, который будет показан, а затем получить его магазин, если магазин загрузился, затем вызовите обработчик, в противном случае зарегистрируйте список load прямо на нем. Обратите внимание, что здесь объект будет ProductList не product-list-view.

+0

это решение не работает, потому что для магазина установлено значение автозагрузки: true , а также хранилище, нажатое на экран, только когда пользователь нажимает на главный экран. Таким образом, хранилище загружается уже до инициализированного списка – CoolMonster

+0

@CoolMonster. Я обновил выше, чтобы использовать «show» вместо этого, а также проверить, загружен ли магазин. Надеюсь, это соответствует вашим требованиям более близко. – MattGoldspink

+0

Спасибо. Это то, что я сделал до сих пор. Но я хочу знать, есть ли другой способ сделать это. – CoolMonster