I have a CompositeView that I am working with in Marionette that when the collection fetches can potentially pull 1000s of records back from the API. The problem I am seeing is that when the UI loads, the browser wigs out and the script freezes the browser up.
I have tried following this blog post (http://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/), but can't seem to figure out how to translate that to working in Marionette.
Here is my CompositeView:
var EmailsMenuView = Marionette.CompositeView.extend({
template: _.template(templateHTML),
childView: EmailItemView,
childViewOptions: function(model, index){
return {
parentIndex: index,
parentContainer: this.$el.closest('form')
};
},
childViewContainer: '.emails',
ui: {
emails: '.emails',
options: '.email-options',
subject: "#subject_line",
fromName: "#from_name",
fromEmail: "#from_email",
thumbnail: '.thumbnail img',
emailName: '.thumbnail figcaption'
},
events: {
'change #ui.subject': 'onSubjectChange',
'change #ui.fromName': 'onFromNameChange',
'change #ui.fromEmail': 'onFromEmailChange'
},
childEvents: {
'menu:selected:email': 'onMenuEmailSelect'
},
collectionEvents: {
'change:checked': 'onEmailSelected'
},
behaviors: {
EventerListener: {
behaviorClass: EventerListener,
eventerEvents: {
'menu:next-click': 'onNext',
'menu:previous-click': 'onPrev'
}
},
LoadingIndicator: {
behaviorClass: LoadingIndicator,
parentClass: '.emails'
}
},
renderItem: function(model) {
console.log(model);
},
/**
* Runs automatically during a render
* #method EmailsMenuView.onRender
*/
onRender: function () {
var colCount, showGridList, selected,
threshold = 300;
if(this.model.get('id')) {
selected = this.model;
}
// refresh its list of emails from the server
this.collection.fetch({
selected: selected,
success: function (collection) {
colCount = collection.length;
console.log(colCount);
},
getThumbnail: colCount <= threshold
});
this.collection.each(this.renderItem);
var hasEmail = !!this.model.get('id');
this.ui.emails.toggle(!hasEmail);
this.ui.options.toggle(hasEmail);
eventer.trigger(hasEmail ? 'menu:last' : 'menu:first');
}
});
My ItemView looks like this:
var EmailItemView = Marionette.ItemView.extend({
tagName: 'article',
template: _.template(templateHTML),
ui: {
radio: 'label input',
img: 'figure img',
figure: 'figure'
},
events: {
'click': 'onSelect',
'click #ui.radio': 'onSelect'
},
modelEvents: {
'change': 'render'
},
behaviors: {
Filter: {
behaviorClass: Filter,
field: "email_name"
}
},
/**
* initializes this instance with passed options from the constructor
* #method EmailItemView.initialize
*/
initialize: function(options){
this.parentIndex = options.parentIndex;
this.parentContainer = options.parentContainer;
this.listenTo(eventer, 'menu:scroll', this.onScroll, this);
},
/**
* Runs automatically when a render happens. Sets classes on root element.
* #method EmailItemView.onRender
*/
onRender: function () {
var checked = this.model.get("checked");
this.$el.toggleClass('selected', checked);
this.ui.radio.prop('checked', checked);
},
/**
* Runs after the first render, only when a dom refrsh is required
* #method EmailItemView.onDomRefresh
*/
onDomRefresh: function(){
this.onScroll();
},
/**
* Marks this item as checked or unchecked
* #method EmailItemView.onSelect
*/
onSelect: function () {
this.model.collection.checkSingle(this.model.get('id'));
this.trigger('menu:selected:email');
},
templateHelpers: {
formattedDate: function() {
var date = this.updated_ts.replace('#D:', '');
if (date !== "[N/A]") {
return new Moment(date).format('dddd, MMMM DD, YYYY [at] hh:mm a');
}
}
},
/**
* Delays the load of this view's thumbnail image until it is close to
* being scrolled into view.
* #method EmailItemView.onScroll
*/
onScroll: function () {
if (this.parentIndex < 10) {
// if it's one of the first items, just load its thumbnail
this.ui.img.attr('src', this.model.get('thumbnail') + '?w=110&h=110');
} else if (this.parentContainer.length && !this.ui.img.attr('src')) {
var rect = this.el.getBoundingClientRect(),
containerRect = this.parentContainer[0].getBoundingClientRect();
// determine if element is (or is about to be) visible, then
// load thumbnail image
if (rect.top - 300 <= containerRect.bottom) {
this.ui.img.attr('src', this.model.get('thumbnail') + '?w=110&h=110');
}
}
}
});
I am trying to adjust my CompositeView to work where I can build the HTML and then render the cached HTML versus appending 1000s of elements
Render all 1000 elements isn't good idea - DOM will become too big. Also on fetch there are parse for all 1000 models, and it works synchroniously. So there are two ways - load less data, or splist data to parse/render by chunks
Related
Actually I'm going to implement a tree view, where the user should have the option to reorder the structure with drag and drop. Actually I can't figure out how to enable drag and drop. I found a lot of examples using the 'treeviewdragdrop' plugin, which is just working with the classic toolkit.
The following Code made me move the first node but not more.
this.toParentSource = new Ext.drag.Source({
element: this.getView().element.down('.x-gridcell'),
constrain: {
element: this.getView().body,
vertical: true
}
});
Can you help me with this problem? I'm using ExtJS 6.5.2 modern toolkit.
This is how I enabled drag and drop for trees in modern Ext JS:
First I've written a plugin which creates the sources that should be draggable.
Plugin
Ext.define('test.component.plugin.TreeDragger', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.treedrag',
mixins: ['Ext.mixin.Observable'],
constructor: function (config) {
this.mixins.observable.constructor.call(this, config);
},
init: function (component) {
var me = this;
this.source = new Ext.drag.Source({
element: component.element,
handle: '.x-gridrow',
constrain: {
element: true,
vertical: true
},
describe: function (info) {
var row = Ext.Component.from(info.eventTarget, component);
info.row = row;
info.record = row.getRecord();
},
proxy: {
type: 'placeholder',
getElement: function (info) {
console.log('proxy: getElement');
var el = Ext.getBody().createChild({
style: 'padding: 10px; width: 100px; border: 1px solid gray; color: red;',
});
el.show().update(info.record.get('description'));
return el;
}
},
// autoDestroy: false,
listeners: {
scope: me,
beforedragstart: me.makeRelayer('beforedragstart'),
dragstart: me.makeRelayer('dragstart'),
dragmove: me.makeRelayer('dragmove'),
dragend: me.makeRelayer('dragend')
}
});
},
disable: function () {
this.source.disable();
},
enable: function () {
this.source.enable();
},
doDestroy: function () {
Ext.destroy(this.source);
this.callParent();
},
makeRelayer: function (name) {
var me = this;
return function (source, info) {
return me.fireEvent(name, me, info);
};
}
});
Next I used this plugin inside my tree.
Tree
xtype: 'tree',
hideHeaders: true,
plugins: {
treedrag: {
type: 'treedrag',
listeners: {
beforedragstart: function (plugin, info) {
// logic to identify the root and prevent it from being moved
console.log('listeners: beforedragstart');
}
}
}
},
columns: [{
xtype: 'treecolumn',
flex: 1,
}
]
Then I defined the drop targets inside the controller.
Controller
afterLoadApportionmentObjectsForTree: function (succes) {
if (succes) {
tree = this.getView().down('tree');
if (tree) {
tree.expandAll();
tree.updateHideHeaders(tree.getHideHeaders());
var store = tree.getStore();
store.remoteFilter = false;
store.filterer = 'bottomup';
this.createDropTargets();
}
}
},
createDropTargets: function () {
var me = this,
rows = tree.innerItems;
Ext.each(rows, function (el) {
var target = new Ext.drag.Target({
element: el.element,
listeners: {
scope: me,
drop: me.onDrop,
beforeDrop: me.onBeforeDrop
}
});
});
},
onDrop: function (target, info, eOpts) {
var source = info.record,
row = Ext.Component.from(target.getElement(), tree),
destination = row.getRecord(),
parentNode = source.parentNode;
destination.appendChild(source);
destination.expand();
if (!parentNode.hasChildNodes()) {
parentNode.set('leaf', true);
}
},
onBeforeDrop: function (target, info, eOpts) {
var source = info.record,
row = Ext.Component.from(target.getElement(), tree),
destination = row.getRecord();
// prevent the user to drop the node on itself
// this would lead to an error caused by recursive method calls
if (source == destination) {
return false;
}
// prevent the user to drop a node on it's children
// this would lead to an error caused by recursive method calls
if (source.findChild('number', destination.get('number'), true) != null) {
return false;
}
return true;
}
I'm using selection Xtype and checkbox type property (CQ.form.Selection) to create a checkbox group in CQ5 (API docs at http://docs.adobe.com/docs/en/cq/5-6/widgets-api/index.html?class=CQ.form.Selection).
But I want to override setValue, getValue and validate functions of it in order to meet my requirement. How can I do that via JCR node declaration ?
many thanks and appreciate.
Not sure what you mean by "do that via JCR node declaration". But if you need to make a few additional steps with standard xtype you just need to create a custom xtype, which wraps the standard one, and use it.
Here is an example of JS-code that creates and registers new xtype (combines values of 2 different fields into a single value).
Ejst.CustomWidget = CQ.Ext.extend(CQ.form.CompositeField, {
/**
* #private
* #type CQ.Ext.form.TextField
*/
hiddenField: null,
/**
* #private
* #type CQ.Ext.form.ComboBox
*/
allowField: null,
/**
* #private
* #type CQ.Ext.form.TextField
*/
otherField: null,
constructor: function(config) {
config = config || { };
var defaults = {
"border": false,
"layout": "table",
"columns":2
};
config = CQ.Util.applyDefaults(config, defaults);
Ejst.CustomWidget.superclass.constructor.call(this, config);
},
// overriding CQ.Ext.Component#initComponent
initComponent: function() {
Ejst.CustomWidget.superclass.initComponent.call(this);
this.hiddenField = new CQ.Ext.form.Hidden({
name: this.name
});
this.add(this.hiddenField);
this.allowField = new CQ.form.Selection({
type:"select",
cls:"ejst-customwidget-1",
listeners: {
selectionchanged: {
scope:this,
fn: this.updateHidden
}
},
optionsProvider: this.optionsProvider
});
this.add(this.allowField);
this.otherField = new CQ.Ext.form.TextField({
cls:"ejst-customwidget-2",
listeners: {
change: {
scope:this,
fn:this.updateHidden
}
}
});
this.add(this.otherField);
},
// overriding CQ.form.CompositeField#processPath
processPath: function(path) {
console.log("CustomWidget#processPath", path);
this.allowField.processPath(path);
},
// overriding CQ.form.CompositeField#processRecord
processRecord: function(record, path) {
console.log("CustomWidget#processRecord", path, record);
this.allowField.processRecord(record, path);
},
// overriding CQ.form.CompositeField#setValue
setValue: function(value) {
var parts = value.split("/");
this.allowField.setValue(parts[0]);
this.otherField.setValue(parts[1]);
this.hiddenField.setValue(value);
},
// overriding CQ.form.CompositeField#getValue
getValue: function() {
return this.getRawValue();
},
// overriding CQ.form.CompositeField#getRawValue
getRawValue: function() {
if (!this.allowField) {
return null;
}
return this.allowField.getValue() + "/" +
this.otherField.getValue();
},
// private
updateHidden: function() {
this.hiddenField.setValue(this.getValue());
}
});
// register xtype
CQ.Ext.reg('ejstcustom', Ejst.CustomWidget);
Creating custom xtype in AEM6's touch UI
I am trying to add in the current position of the device into the proxy call. I have already added in variables with '+radius+' and '+values+'. I have used Ext.util.Geolocation and can see the geolocation in the console. How do i get a lat and long variable out of this so i can add to the proxy like '+lat+' and '+lon+'
Ext.define('FirstApp.controller.History', {
extend:'Ext.app.Controller',
config:{
refs:{
main:'main',
placesContainer:'placesContainer',
placesList:'placesContainer places list',
info:'info',
review:'review',
rss:'rss',
favourites:'favourites',
mapcontainer:'mapcontainer',
visit: '#visit',
radius: '#radius'
},
control:{
'placesContainer places list':{
itemtap:'recordDetailsNavigation'
},
'main':{
activeitemchange:'recordTabChanged'
},
'#home': {
// On the tap event, call onNewTap
tap: 'onHomeTap'
},
'#info': {
// On the tap event, call onNewTap
tap: 'onInfoTap'
}
,
'#search': {
// On the tap event, call onNewTap
tap: 'onSearchTap'
}
,
'#leaveReview': {
// On the tap event, call onNewTap
tap: 'onReviewTap'
}
},
routes: {
'placesContainer': 'gotoPlacesContainer',
'placesContainer/:id': 'gotoPlacesContainerDetails',
'info': 'gotoInfo',
'review': 'gotoReview',
'rss': 'gotoRss',
'favourites': 'gotoFavourites',
'mapcontainer': 'gotoMapContainer'
}
},
recordDetailsNavigation:function (list, index, target, record) {
console.log("recordDetailsNavigation");
this.getApplication().getHistory().add(Ext.create('Ext.app.Action', {
url:'placesContainer/' + record.get('id')
}),true);
},
recordTabChanged:function(tab,value, oldValue){
console.log("recordTabChanged "+value.xtype);
this.getApplication().getHistory().add(Ext.create('Ext.app.Action', {
url:value.xtype
}),true);
},
gotoPlacesContainer:function(){
console.log('Goto PlacesContainer');
this.getMain().setActiveItem(0);
var items = this.getPlacesContainer().getItems();
console.log("PlacesContainer has "+items.length+" children")
if(items.length>1){
this.getPlacesContainer().pop();
}
},
gotoReview:function(){
console.log('Goto Review');
this.getMain().setActiveItem(1);
Reviews.load();
},
gotoMapContainer:function(){
console.log('Goto MapContainer');
this.getMain().setActiveItem(2);
},
gotoPlacesContainerDetails:function(id){
console.log('Goto PlacesContainer Details for id '+id);
this.gotoPlacesContainer();
this.getPlacesList().refresh();
this.getPlacesList().on('refresh',function(){
var store = Ext.getStore('Places');
var index = store.find('id',id);
var record = store.getAt(index)
this.getPlacesContainer().push({
xtype:'details',
title:record.data.name,
data:record.data
})
this.getApplication().getHistory().add(Ext.create('Ext.app.Action', {
url:'placesContainer/' + record.get('id')
}),true);
},this);
},
gotoInfo:function(){
console.log('Goto Info');
this.getMain().setActiveItem(3);
},
gotoRss:function(){
console.log('Goto Rss');
this.getMain().setActiveItem(4);
},
gotoFavourites:function(){
console.log('Goto Favourites');
this.getMain().setActiveItem(5);
},
onHomeTap: function() {
Ext.Viewport.setActiveItem(Ext.create('FirstApp.view.Home'));
},
onReviewTap: function() {
Ext.Viewport.setActiveItem(Ext.create('FirstApp.view.CreateReview'));
},
onInfoTap: function() {
Ext.Viewport.setActiveItem(Ext.create('FirstApp.view.Info'));
},
onSearchTap: function() {
Ext.Viewport.setActiveItem(Ext.create('FirstApp.view.Main'));
var values = this.getVisit().getValue();
var radius = this.getRadius().getValue() * 1000;
console.log(values);
console.log(radius);
var proxy = {
type:'ajax',
id:'myPlaceProxy',
url:'https://maps.googleapis.com/maps/api/place/search/json? location=52.247983,-7.141113&radius='+radius+'&types='+values+'&name=&sensor=false&key=',
reader:{
type:'json',
rootProperty:'results'
}
}
var geo = new Ext.util.Geolocation({
autoUpdate: false,
allowHighAccuracy: true,
listeners: {
locationupdate: function(geo) {
lat = geo.getLatitude();
lon = geo.getLongitude();
var proxy = Ext.getCmp('myPlaceProxy');
proxy.setUrl('https://maps.googleapis.com/maps/api/place/search/json?location='+lat+','+lon+'&radius='+radius+'&types='+values+'&name=&sensor=false&key=AIzaSyAAStZvDJ_5ENODEdSCanLWgJBG6p6eXBQ');
console.log(proxy);
Ext.StoreMgr.get('Places').setProxy(proxy);
Ext.StoreMgr.get('Places').load();
}
}
});
geo.updateLocation();
}
});
Ext.define('FirstApp.store.Places',{
extend:'Ext.data.Store',
config:{
autoLoad:false,
model:'FirstApp.model.Place',
proxy:{
}
}
})
First of all give id to your proxy so that we can access it via id anytime
var proxy = {
type:'ajax',
id:'myPlaceProxy',
url:'https://maps.googleapis.com/maps/api/place/search/json?location=52.247983,-7.141113&radius='+radius+'&types='+values+'&name=&sensor=false&key=',
reader:{
type:'json',
rootProperty:'results'
}
}
then in you geo location's locationupdate event access the proxy
var geo = new Ext.util.Geolocation({
autoUpdate: true,
allowHighAccuracy: true,
listeners: {
locationupdate: function(geo) {
lat = geo.getLatitude();
lon = geo.getLongitude();
var proxy = Ext.getCmp('myPlaceProxy');
proxy.setUrl('https://maps.googleapis.com/maps/api/place/search/json?location='+lat+','+lon+'&radius='+radius+'&types='+values+'&name=&sensor=false&key='');
console.log(proxy);
Ext.StoreMgr.get('Places').setProxy(proxy);
Ext.StoreMgr.get('Places').load();
}
}
});
then fire locationupdate event of your geo when ever you want by calling this
geo.updateLocation();
EDIT:
but i strongly recomment that dont always create var geo
you just have to call this geo.updateLocation(); on tap once you create it globally, in that way you can manage it much better
Try this:
Ext.define('FirstApp.store.Places',{
extend:'Ext.data.Store',
id: 'myPlaces',
config:{
autoLoad:false,
model:'FirstApp.model.Place',
proxy:{
type:'ajax',
url:'https://maps.googleapis.com/maps/api/place/search/json? location=52.247983,-7.141113&radius='+radius+'&types='+values+'&name=&sensor=false&key=AIzaSyAAStZvDJ_5ENODEdSCanLWgJBG6p6eXBQ',
reader:{
type:'json',
rootProperty:'results'
}
}
});
after that you can set the url in the tap event as
onSearchTap: function() {
Ext.Viewport.setActiveItem(Ext.create('FirstApp.view.Main'));
var values = this.getVisit().getValue();
var radius = this.getRadius().getValue() * 1000;
console.log(values);
console.log(radius);
var geo = new Ext.util.Geolocation({
autoUpdate: false,
allowHighAccuracy: true,
listeners: {
locationupdate: function(geo) {
lat = geo.getLatitude();
lon = geo.getLongitude();
Ext.StoreMgr.get('Places').getProxy().setUrl('https://maps.googleapis.com/maps/api/place/search/json?location='+lat+','+lon+'&radius='+radius+'&types='+values+'&name=&sensor=false&key='');
Ext.StoreMgr.get('Places').load();
}
}
});
geo.updateLocation();
}
I am using extjs 4.0 and having a combobox with queryMode 'remote'. I fill it with data from server. The problem is that the number of records from server is too large, so I thought it would be better to load them by parts. I know there is a standart paginator tool for combobox, but it is not convinient because needs total number of records.
Is there any way to add dynamic scrolling for combobox? When scrolling to the bottom of the list I want to send request for the next part of records and add them to the list. I can not find appropriate listener to do this.
The following is my solution for infinite scrolling for combobox, Extjs 4.0
Ext.define('TestProject.testselect', {
extend:'Ext.form.field.ComboBox',
alias: ['widget.testselect'],
requires: ['Ext.selection.Model', 'Ext.data.Store'],
/**
* This will contain scroll position when user reaches the bottom of the list
* and the store begins to upload data
*/
beforeRefreshScrollTop: 0,
/**
* This will be changed to true, when there will be no more records to upload
* to combobox
*/
isStoreEndReached : false,
/**
* The main thing. When creating picker, we add scroll listener on list dom element.
* Also add listener on load mask - after load mask is hidden we set scroll into position
* that it was before new items were loaded to list. This prevents 'jumping' of the scroll.
*/
createPicker: function() {
var me = this,
picker = me.callParent(arguments);
me.mon(picker, {
'render' : function() {
Ext.get(picker.getTargetEl().id).on('scroll', me.onScroll, me);
me.mon(picker.loadMask, {
'hide' : function() {
Ext.get(picker.id + '-listEl').scroll("down", me.beforeRefreshScrollTop, false);
},
scope: me
});
},
scope: me
});
return picker;
},
/**
* Method which is called when user scrolls the list. Checks if the bottom of the
* list is reached. If so - sends 'nextPage' request to store and checks if
* any records were received. If not - then there is no more records to load, and
* from now on if user will reach the bottom of the list, no request will be sent.
*/
onScroll: function(){
var me = this,
parentElement = Ext.get(me.picker.getTargetEl().id),
parentElementTop = parentElement.getScroll().top,
scrollingList = Ext.get(me.picker.id+'-items');
if(scrollingList != undefined) {
if(!me.isStoreEndReached && parentElementTop >= scrollingList.getHeight() - parentElement.getHeight()) {
var multiselectStore = me.getStore(),
beforeRequestCount = multiselectStore.getCount();
me.beforeRefreshScrollTop = parentElementTop;
multiselectStore.nextPage({
params: this.getParams(this.lastQuery),
callback: function() {
me.isStoreEndReached = !(multiselectStore.getCount() - beforeRequestCount > 0);
}
});
}
}
},
/**
* Took this method from Ext.form.field.Picker to collapse only if
* loading finished. This solve problem when user scrolls while large data is loading.
* Whithout this the list will close before finishing update.
*/
collapse: function() {
var me = this;
if(!me.getStore().loading) {
me.callParent(arguments);
}
},
/**
* Reset scroll and current page of the store when loading all profiles again (clicking on trigger)
*/
doRawQuery: function() {
var me = this;
me.beforeRefreshScrollTop = 0;
me.getStore().currentPage = 0;
me.isStoreEndReached = false;
me.callParent(arguments);
}
});
When creating element, should be passed id to the listConfig, also I pass template for list, because I need it to be with id. I didn't find out more elegant way to do this. I appreciate any advice.
{
id: 'testcombo-multiselect',
xtype: 'testselect',
store: Ext.create('TestProject.testStore'),
queryMode: 'remote',
queryParam: 'keyword',
valueField: 'profileToken',
displayField: 'profileToken',
tpl: Ext.create('Ext.XTemplate',
'<ul id="ds-profiles-boundlist-items"><tpl for=".">',
'<li role="option" class="' + Ext.baseCSSPrefix + 'boundlist-item' + '">',
'{profileToken}',
'</li>',
'</tpl></ul>'
),
listConfig: {
id: 'testcombo-boundlist'
}
},
And the store:
Ext.define('TestProject.testStore',{
extend: 'Ext.data.Store',
storeId: 'teststore',
model: 'TestProject.testModel',
pageSize: 13, //the bulk of records to receive after each upload
currentPage: 0, //server side works with page numeration starting with zero
proxy: {
type: 'rest',
url: serverurl,
reader: 'json'
},
clearOnPageLoad: false //to prevent replacing list items with new uploaded items
});
Credit to me1111 for showing the way.
Ext.define('utils.fields.BoundList', {
override:'Ext.view.BoundList',
///#function utils.fields.BoundList.loadNextPageOnScroll
///Add scroll listener to load next page if true.
///#since 1.0
loadNextPageOnScroll:true,
///#function utils.fields.BoundList.afterRender
///Add scroll listener to load next page if required.
///#since 1.0
afterRender:function(){
this.callParent(arguments);
//add listener
this.loadNextPageOnScroll
&&this.getTargetEl().on('scroll', function(e, el){
var store=this.getStore();
var top=el.scrollTop;
var count=store.getCount()
if(top>=el.scrollHeight-el.clientHeight//scroll end
&&count<store.getTotalCount()//more data
){
//track state
var page=store.currentPage;
var clearOnPageLoad=store.clearOnPageLoad;
store.clearOnPageLoad=false;
//load next page
store.loadPage(count/store.pageSize+1, {
callback:function(){//restore state
store.currentPage=page;
store.clearOnPageLoad=clearOnPageLoad;
el.scrollTop=top;
}
});
}
}, this);
},
});
You can implement the infinite grid as list of the combobox.
Look at this example to implement another picker:
http://www.sencha.com/forum/showthread.php?132328-CLOSED-ComboBox-using-Grid-instead-of-BoundList
If anyone needs this in ExtJS version 6, here is the code:
Ext.define('Test.InfiniteCombo', {
extend: 'Ext.form.field.ComboBox',
alias: ['widget.infinitecombo'],
/**
* This will contain scroll position when user reaches the bottom of the list
* and the store begins to upload data
*/
beforeRefreshScrollTop: 0,
/**
* This will be changed to true, when there will be no more records to upload
* to combobox
*/
isStoreEndReached: false,
/**
* The main thing. When creating picker, we add scroll listener on list dom element.
* Also add listener on load mask - after load mask is hidden we set scroll into position
* that it was before new items were loaded to list. This prevents 'jumping' of the scroll.
*/
createPicker: function () {
var me = this,
picker = me.callParent(arguments);
me.mon(picker, {
'afterrender': function () {
picker.on('scroll', me.onScroll, me);
me.mon(picker.loadMask, {
'hide': function () {
picker.scrollTo(0, me.beforeRefreshScrollTop,false);
},
scope: me
});
},
scope: me
});
return picker;
},
/**
* Method which is called when user scrolls the list. Checks if the bottom of the
* list is reached. If so - sends 'nextPage' request to store and checks if
* any records were received. If not - then there is no more records to load, and
* from now on if user will reach the bottom of the list, no request will be sent.
*/
onScroll: function () {
var me = this,
parentElement = me.picker.getTargetEl(),
scrollingList = Ext.get(me.picker.id + '-listEl');
if (scrollingList != undefined) {
if (!me.isStoreEndReached && me.picker.getScrollY() + me.picker.getHeight() > parentElement.getHeight()) {
var store = me.getStore(),
beforeRequestCount = store.getCount();
me.beforeRefreshScrollTop = me.picker.getScrollY();
store.nextPage({
params: this.getParams(this.lastQuery),
callback: function () {
me.isStoreEndReached = !(store.getCount() - beforeRequestCount > 0);
}
});
}
}
},
/**
* Took this method from Ext.form.field.Picker to collapse only if
* loading finished. This solve problem when user scrolls while large data is loading.
* Whithout this the list will close before finishing update.
*/
collapse: function () {
var me = this;
if (!me.getStore().loading) {
me.callParent(arguments);
}
},
/**
* Reset scroll and current page of the store when loading all profiles again (clicking on trigger)
*/
doRawQuery: function () {
var me = this;
me.beforeRefreshScrollTop = 0;
me.getStore().currentPage = 1;
me.isStoreEndReached = false;
me.callParent(arguments);
}
});
First of all thanks to #me1111 for posting the code for dynamic rendering on scroll. That code is working for me after doing a small change.
tpl: Ext.create('Ext.XTemplate',
'<ul id="testcombo-boundlist-items"><tpl for=".">',
'<li role="option" class="' + Ext.baseCSSPrefix + 'boundlist-item' + '">',
'{profileToken}',
'</li>',
'</tpl></ul>'
),
listConfig: {
id: 'testcombo-boundlist'
}
in code from <ul id="ds-profiles-boundlist-items"><tpl for="."> i have changed id to "testcombo-boundlist-items". as we defined id as 'testcombo-boundlist' in listConfig.
Before modification, in onScroll method scrollingList = Ext.get(me.picker.id + '-items'); i am getting scrollList as a null. because me.picker.id will return 'testcombo-boundlist' on this we are appending '-items' so it became 'testcombo-boundlist-items' but this id does not exists. so iam getting null.
After modification of id in <ul id="testcombo-boundlist-items"> we have a list object on "testcombo-boundlist-items". so i got a object.
Hope this small change will help.
Is there any way to access the parent component (via this.ownerCt) in the initComponent function?
While trying to access it via this.ownerCt, i found out that the ownerCt attribute is set after initComponent. So I do not know how i can hook in the initialization process of my component where i can change some parent's attributes.
I know this doesn't answer the question directly. I would have placed this in the comments to your question but I'm not allowed yet it would appear. If you are building breadcrumbs. I would look at extending the tab panel and creating a plugin for the Tab Bar that creates the kinda of navigation you want.
Ext.define('HOD.plugins.Breadcrumbs', {
// private
init : function(tabBar) {
tabBar.on('beforeadd', this.addIcons, this);
tabBar.on('beforeremove', this.handleTabRemove, this);
},
addIcons: function(tabBar, newTab, index, options) {
if (index > 0) {
newTab.iconCls = 'icon-arrow';
tabBar.items.each(function(tab) {
if (tab != newTab) {
tab.overCls = 'breadcrumbs-over'
}
});
}
},
handleTabRemove: function(tabBar, oldTab, options) {
var count = tabBar.items.getCount();
if (count > 1) {
var newTab = tabBar.items.getAt(count-2);
newTab.overCls = '';
newTab.removeCls('x-tab-breadcrumbs-over');
}
}
});
Then extend the tab panel so it uses the above plugin to style the tabs correctly.
Ext.define('HOD.view.GlobalNavigation', {
extend: 'Ext.tab.Panel',
border: false,
alias: 'widget.content',
requires: ['HOD.plugins.Breadcrumbs'],
tabBar: {
cls: 'breadcrumbs',
plugins: ['tabbarbreadcrumbs']
},
initComponent: function() {
this.on('tabchange', this.handleTabChange, this);
this.callParent(arguments);
},
push: function(tab) {
this.add(tab);
this.setActiveTab(tab);
},
pop: function() {
// Get the current cards;
var cards = this.getLayout().getLayoutItems();
if (cards.length > 1) {
this.setActiveTab(cards[cards.length-2]);
}
},
handleTabChange: function (tabPanel, newCard, oldCard, options) {
var cards = tabPanel.getLayout().getLayoutItems();
for (var i = (cards.length - 1); i > 0; i--) {
if (cards[i] !== newCard) {
this.remove(cards[i]);
} else {
break;
}
}
}
});
I've written up post about it here if you need more detail.
I would not recommend changing anything in the container from the inside element functions. Instead I would create an event in the element, fire that event and listen for it in the container.
This way your component will notify the container to do something, and container will do it itself.