EXTJS 4: Adding listeners to elements not consistent - extjs

I'm working with an EXTJS 4 dataview and having inconsistent results when adding listeners to html elements (links) in each data node. I have placed the code in the load listener on the store that is tied to the dataview. It appears to work on the first load but subsequent loads get worse as it begins missing some elements. Each time a call store.reload() it gets worse.
I have verified in firebug that the html element ID's are rendering properly but for some reason when I reload the store it begins to miss some elements at first, then all elements. Code for the load listener below:
listeners: {
load: function(store, records, successful, options){
var nodes = records;
for (i=0, len = nodes.length; i < len;i++){
var id = nodes[i].data.id;
var addtocartel = Ext.get('img-cart-'+id);
var viewel = Ext.get('img-view-'+id);
//Setting hidden class for nonimage items
switch (nodes[i].data.type) {
case 'image' :
viewel.addCls('imgprf');
addtocartel.addCls('cartprf');
break;
default :
viewel.addCls('sc_hidden');
addtocartel.addCls('sc_hidden');
viewel.hide();
addtocartel.hide();
break;
}
if(addtocartel !== null){
addtocartel.itemid = id;
addtocartel.on('click', function(e,t){
var el = Ext.get(t);
var imgrec = imagestore.getById(el.itemid);
e.stopEvent();
prfproductwindow.show();
});
}
if(viewel !== null){
viewel.itemid = id;
viewel.on('click', function(e,t){
var el = Ext.get(t);
var imgrec = imagestore.getById(el.itemid);
});
}
}
}
}

Refreshes to the grid view can happen without any sort of load occurring. When the grid view refreshes it wipes out the existing html elements and creates new ones, so any listeners you had attached to those elements will be useless.
You should look into adding a click listener to your entire grid and using a delegate to listen for clicks on specific html elements within the view. This will allow you to add a single listener once that will always work no matter how many times the elements within the view are rerendered.
grid.getView().getEl().on('click', function(evt, target) {
console.log('clicked on ' + target);
}, {delegate: '.my-css-selector-for-some-element'});
The click handler will only be fired for clicks on elements that match the delegate selector.
Also, the logic where you are adding css classes based on the record's type should be done in the renderer (if you have a grid) or handled by the data view's template.

Related

ExtJS 7 - Column filter issue with locked column

I encountered this bug where the column filter is incorrect if the grid has a locked column
Here's the fiddle: sencha fillde
Steps to reproduce:
(Do not apply any filter)
Open the "Email" column menu
Open "Name" column menu (this is the locked column)
Open "Phone" column menu (notice that the filter menu is incorrect, it is showing the filter for "Email" column).
For grid that has no 'locked' columns the filter menu is working fine, thanks for anyone who can help!
Okay, this one was a bit tricky. It turns out that for a locked grid, the Ext.grid.filters.Filters:onMenuCreate gets hit twice... one for each side of the grid's menu that shows. The problem is that in the onMenuCreate, the framework doesn't account for the 2 menus. It only cares about the last menu that gets created and destroys the previous menu's listeners. In onMenuBeforeShow, the framework does account for each side of the grid, so I extended this idea into an override. I would encourage you to create a Sencha Support ticket for this, and if you don't have access, let me know, so I can submit one. Fiddle here.
Ext.override(Ext.grid.filters.Filters, {
onMenuCreate: function (headerCt, menu) {
var me = this;
// TODO: OLD BAD CODE... this would destroy the first menu's listeners
// if (me.headerMenuListeners) {
// Ext.destroy(me.headerMenuListeners);
// me.headerMenuListeners = null;
// }
// me.headerMenuListeners = menu.on({
// beforeshow: me.onMenuBeforeShow,
// destroyable: true,
// scope: me
// });
// Just like in the onMenuBeforeShow, we need to create a hash of our menus
// and their listeners... if we don't, we remove the 1st menu's listeners
// when the 2nd menu is created
if (!me.headerMenuListeners) {
me.headerMenuListeners = {};
}
var parentTableId = headerCt.ownerCt.id;
var menuListener = me.headerMenuListeners[parentTableId];
if (menuListener) {
Ext.destroy(menuListener);
me.headerMenuListeners[parentTableId] = null;
}
me.headerMenuListeners[parentTableId] = menu.on({
beforeshow: me.onMenuBeforeShow,
destroyable: true,
scope: me
});
},
destroy: function () {
var me = this,
filterMenuItem = me.filterMenuItem,
item;
// TODO: ADDING THIS AND REMOVING FROM THE Ext.destroy on the next line
var headerMenuListeners = this.headerMenuListeners;
Ext.destroy(me.headerCtListeners, me.gridListeners);
me.bindStore(null);
me.sep = Ext.destroy(me.sep);
for (item in filterMenuItem) {
filterMenuItem[item].destroy();
}
// TODO: ADDING THIS AND REMOVING FROM THE Ext.destroy on the next line
for (item in headerMenuListeners) {
headerMenuListeners[item].destroy();
}
this.callParent();
}
});

Hide DateField while clicking anywhere in page

I am trying to hide extjs date-field on clicking anywhere on DOM except date-field. while clicking anywhere in dom bodyClick function get called.On basis of page co-ordinates element object get retrieved and then this element object get compared with date-field object.This works fine but problem comes whenever i am clicking on date-picker again "date-field" get hide.
sample code -
bodyClick: function(e){
var me = this, elem, t;
var flag =true;
elem = me.getEl();
for(t = Ext.dom.Element.fromPoint(e.getX(), e.getY()); t && t != null;){
if (Ext.fly(elem ).contains(t)){
flag =false;
}
}
if(flag ){
me.hide();
}
}
Any Suggestions for hiding datefield while clicking anywhere in DOM (extJs).
You can try this in afterRender of the panel or container in which your component is in.
this.mon(Ext.getBody().getEl(), 'click', this.yourFunction, this);
yourFunction:function(e){
var comp = Ext.ComponentQuery.query('datepicker')[0];//Get your datepicker component
if (Ext.fly(e.getTarget()) != comp) { //get the target using Ext.fly
comp.hide(); //Hide the component if the target is not the datepicker
}
}
Hope this helps you.

How do I reset all filters in Extjs Grids?

How do I reset my ExtJS filters in my grids. More specifically, how do I get the header to honour the changes to the filtering.
ie. This works fine :
grid.store.clearFilter();
But the header rendering is all wrong. I need to get into all the menu objects and unselect the checkboxes.
I am getting pretty lost. I am pretty sure this gives me the filterItems :
var filterItems = grid.filters.filters.items;
And from each of these filter items, i can get to menu items like so :
var menuItems = filter.menu.items;
But that's as far as I can get. I am expecting some kind of checkbox object inside menu items, and then I can uncheck that checkbox, and hopefully the header rendering will then change.
UPDATE :
I now have this code. The grid store has its filter cleared. Next I get the filterItems from grid.filters.filters.items and iterate over them. Then I call a function on each of the menu items.
grid.store.clearFilter();
var filterItems = grid.filters.filters.items;
for (var i = 0; i<filterItems.length; i++){
var filter = filterItems[i];
filter.menu.items.each(function(checkbox) {
if (checkbox.setChecked)
checkbox.setChecked(false, true);
});
}
The checkboxes do get called, but still nothing is happening :(
Try this code:
grid.filters.clearFilters();
This should take care of both the grid and its underlying store.
When you do
grid.store.clearFilter();
it can only clear the filters on the store but the grid's view doesn't get updated with that call. Hence to handle it automatically for both the grid's view as well as the grid's store, just use
grid.filters.clearFilters();
Hope it helps!
Cheers!
Your update help me but you forget the case where you have input text instead of checkbox.
So this is my addition of your solution:
grid.filters.clearFilters();
var filterItems = grid.filters.filters.items;
for (var i = 0; i<filterItems.length; i++){
var filter = filterItems[i];
filter.menu.items.each(function(element) {
if (element.setChecked) {
element.setChecked(false, true);
}
if(typeof element.getValue !== "undefined" && element.getValue() !== "") {
element.setValue("");
}
});
}
When you use grid wiht gridfilters plugin
and inovoke
grid.filters.clearFilters();
it reset applyed filters, but it don't clean value in textfield inside menu.
For clean textfield text you can try this:
grid.filters.clearFilters();
const plugin = grid.getPlugin('gridfilters');
let activeFilter;
if('activeFilterMenuItem' in plugin) {
activeFilter = plugin.activeFilterMenuItem.activeFilter
}
if (activeFilter && activeFilter.type === "string") {
activeFilter.setValue("");
}

ExtJS 4.2 Grid Form Binding (updaterecord on form edit)

I have a grid that on selection binds the record to a form.
gridSelectionChange: function (model, records) {
if (records[0]) {
this.getFormdata().getForm().loadRecord(records[0]);
}
},
Everything works fine, but if I change any field value the grid is not updating the record and neither the datastore.
I have read that I have to call:
form.updateRecord();
But how can I call it on every lost of focus of my fields (textfield, combos, etc.)?
Is there a way to do the two way binding?
You can see a working example under Ext JS 4 SDK examples/app/simple/simple.html
It binds a grid to a form inside a window.
This is the code that do the trick:
editUser: function(grid, record) { // this function fires when dblClick on itemRow
var edit = Ext.create('AM.view.user.Edit').show(); //creates a window a shows it
edit.down('form').loadRecord(record); //reference the form and load the record
},
updateUser: function(button) { //this function fires on save button of the form
var win = button.up('window'), //get a reference to the window
form = win.down('form'), // get a reference to the form
record = form.getRecord(), // get the form record
values = form.getValues(); // get the values of the form
record.set(values); //set the values to the record (same object shared with the grid)
win.close(); //close window
this.getUsersStore().sync(); // this line is only necesary if you want to synchronize with the server
}
Bottom line do:
var record = form.getRecord(),
values = form.getValues();
record.set(values);

In Backbone.js how do you handle Ordinal Numbering and changing numbering based on jQuery Sortable in the view?

Here is my situation. I have a bunch of "Question" model inside a "Questions" collection.
The Question Collection is represented by a SurveyBuilder view.
The Question Model is represented by a QuestionBuilder view.
So basically you have an UL of QuestionBuilder views. The UL has a jQuery sortable attached (so you can reorder the questions). The question is once I'm done reordering I want to update the changed "question_number"s in the models to reflect their position.
The Questions collection has a comparator of 'question_number' so collection should be sorted. Now I just need a way to make their .index() in the UL reflect their question_number. Any ideas?
Another problem is DELETEing a question, I need to update all the question numbers. Right now I handle it using:
var deleted_number = question.get('question_number');
var counter = deleted_number;
var questions = this.each(function(question) {
if (question.get('question_number') > deleted_number) {
question.set('question_number', question.get('question_number') - 1);
}
});
if (this.last()) {
this.questionCounter = this.last().get('question_number') + 1;
} else {
this.questionCounter = 1;
}
But it seems there's got to be a much more straighforward way to do it.
Ideally whenever a remove is called on the collection or the sortstop is called on the UL in the view, it would get the .index() of each QuestionuBuilder view, update it's models's question_number to the .index() + 1, and save().
My Models,Views, and Collections: https://github.com/nycitt/node-survey-builder/tree/master/app/js/survey-builder
Screenshot: https://docs.google.com/file/d/0B5xZcIdpJm0NczNRclhGeHJZQkE/edit
More than one way to do this but I would use Backbone Events. Emit an event either when the user clicks something like done sorting, hasn't sorted in N seconds, or as each sort occurs using a jQuery sortable event such as sort. Listen for the event inside v.SurveyBuilder.
Then do something like this. Not tested obviously but should get you there relatively easily. Update, this should handle your deletions as well becuase it doesn't care what things used to be, only what they are now. Handle the delete then trigger this event. Update 2, first examples weren't good; so much for coding in my head. You'll have to modify your views to insert the model's cid in a data-cid attribute on the li. Then you can update the correct model using your collection's .get method. I see you've found an answer of your own, as I said there are multiple approaches.
v.SurveyBuilder = v.Page.extend({
template: JST["app/templates/pages/survey-builder.hb"],
initialize: function() {
this.eventHub = EventHub;
this.questions = new c.Questions();
this.questions.on('add', this.addQuestion, this);
this.eventHub.on('questions:doneSorting', this.updateIndexes)
},
updateIndexes: function(e) {
var that = this;
this.$('li').each(function(index) {
var cid = $(this).attr('data-cid');
that.questions.get(cid).set('question_number', index);
});
}
I figured out a way to do it!!!
Make an array of child views under the parent view (in my example this.qbViews maintains an array of QuestionBuilder views) for the SurveyBuilder view
For your collection (in my case this.questions), set the remove event using on to updateIndexes. That means it will run updateIndexes every time something is removed from this.questions
In your events object in the parent view, add a sortstop event for your sortable object (in my case startstop .question-builders, which is the UL holding the questionBuilder views) to also point to updateIndexes
In updateIndexes do the following:
updateIndexes: function(){
//Go through each of our Views and set the underlying model's question_number to
//whatever the index is in the list + 1
_.each(this.qbViews, function(qbView){
var index = qbView.$el.index();
//Only actually `set`s if it changed
qbView.model.set('question_number', index + 1);
});
},
And there is my full code for SurveyBuilder view:
v.SurveyBuilder = v.Page.extend({
template: JST["app/templates/pages/survey-builder.hb"],
initialize: function() {
this.qbViews = []; //will hold all of our QuestionBuilder views
this.questions = new c.Questions(); //will hold the Questions collection
this.questions.on('add', this.addQuestion, this);
this.questions.on('remove', this.updateIndexes, this); //We need to update Question Numbers
},
bindSortable: function() {
$('.question-builders').sortable({
items: '>li',
handle: '.move-question',
placeholder: 'placeholder span11'
});
},
addQuestion: function(question) {
var view = new v.QuestionBuilder({
model: question
});
//Push it onto the Views array
this.qbViews.push(view);
$('.question-builders').append(view.render().el);
this.bindSortable();
},
updateIndexes: function(){
//Go through each of our Views and set the underlying model's question_number to
//whatever the index is in the list + 1
_.each(this.qbViews, function(qbView){
var index = qbView.$el.index();
//Only actually `set`s if it changed
qbView.model.set('question_number', index + 1);
});
},
events: {
'click .add-question': function() {
this.questions.add({});
},
//need to update question numbers when we resort
'sortstop .question-builders': 'updateIndexes'
}
});
And here is the permalink to my Views file for the full code:
https://github.com/nycitt/node-survey-builder/blob/1bee2f0b8a04006aac10d7ecdf6cb19b29de8c12/app/js/survey-builder/views.js

Resources