Ext js event fired or called after renderer - html

I have a grid column which uses the renderer function. Are the any events fired or called after this? I have tried several ones but they all get called on the whole column and they all fire before the renderer (even event afterrender)
thanks in advance

afterrender only fires once when the column is laid out on the page. It is a basic ExtJS component event that almost all ExtJS components have and doesn't relate to the renderer function used for grid columns.
Not totally sure what you're trying to do this for... but if I wanted to trigger an event whenever my renderer function was executed I would fire a custom event from the renderer function itself. Something like this:
Ext.create('Ext.grid.Panel', {
title: 'After Renderer Event Demo',
store: Ext.getStore('DummyData'),
columns: [{
text: 'Column 1',
dataIndex:'aNumber',
// dummy renderer function that fires an event after execution
renderer: function(value) {
// wrapping in a deferred function so that it fires AFTER
Ext.defer(function() {
this.fireEventArgs('aftercolumnrenderer', arguments);
}, 10);
if (value === 1) {
return '1 person';
}
return value + ' people';
}
}, {
text: 'Column 2',
dataIndex:'aString'
}],
width: 400,
forceFit: true,
renderTo: Ext.getBody()
});
I could listen for it directly with:
myColumn.on('aftercolumnrenderer', function(value, metaData, record, rowIndex, colIndex, store, view) {
// do stuff
});
Or from within a controller's control function if you're using ExtJS MVC.
Also see fireEventArgs and the on method for reference.

Related

Clicking, pasting text and uploading files from extension

So I'm basically developing an automated click-paste-and-upload system for mutiple texts and files inside a google page.
This method helped me get the instances of objects that I'm looking for: buttons, textboxes, richtextboxes, etc.
Now I want to work with them.
So for example I know the id of a button , and the function subscribed to its click event. How do I trigger the click event from the extension ? I've tried injecting a script with the click event handler (discovered with DOM inspector) at "document_startup" but I don't get an error or anything else.
Here's the content script! The loggerhead function should have inserted the script but I don't think it did. What might be the reason for the blow code not giving anything?
// Runs a function for every added DOM element that matches a filter
// filter -- either function(DOM_node){/*...*/}, returns true or false
// OR a jQuery selector
// callback -- function(DOM_node){/*...*/}
function watchNodes(filter, callback){
observer = new MutationObserver( function (mutations) {
mutations.forEach( function (mutation){
if(typeof filter === "function"){
$(mutation.addedNodes).filter(
function(i){ return filter(this); }
).each(
function(i){ callback(this); }
);
} else {
$(mutation.addedNodes).filter(filter).each(
function(i){ callback(this); }
);
}
});
});
// For every added element, a mutation will be processed
// with mutation.taget == parent
// and mutation.addedNodes containing the added element
observer.observe(document, { subtree: true, childList: true });
}
function loggerhead(node) {
console.log("passhead");
//also inject jquery
var jqueryEl = document.createElement('script');
jqueryEl.setAttribute('src', chrome.extension.getURL('jquery-1.11.1.min.js'));
jqueryEl.setAttribute('type', 'text/javascript');
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', chrome.extension.getURL('script.js'));
scriptEl.setAttribute('type', 'text/javascript');
node.appendChild(jqueryEl);
node.appendChild(scriptEl);
}
watchNodes("head", loggerhead);
// method not working
//var gmailHead = jQuery("head", document).get(0);
script.js contains the function of subscribed to the click event of the button that I've managed to find through the DOM inspector:
function Cdb(b){return function(){if(Vbb()){return Ddb(b,this,arguments)}else{var a=Ddb(b,this,arguments);a!=null&&(a=a.val);return a}}}
You should try to call the existing click handler like
buttonElement.click()

pass dom element from background script to chrome.tabs.executeScript

I'm trying to pass the active dom element when the contextmenu is clicked from my background script to a script that is being called through chrome.tabs.executeScript. I can pass booleans and strings just fine, but i always get an error when i pass dom elements. I'm starting to think it's not possible.
//doScripts function called from browser action
chrome.browserAction.onClicked.addListener(function(tab) {
doScripts(true, null);
});
//doScripts function called from context menu click
function getClickHandler(info, tab) {
var currTarg = document.activeElement;
console.log("currTarg = " + currTarg);
doScripts(false, currTarg);
}
//i reference doingBrowserAction and contextTarg in myscript.js
function doScripts(context, targ){
chrome.tabs.executeScript(null, {code: "var doingBrowserAction = "+context+"; var contextTarg = "+targ+";"}, function(){
chrome.tabs.executeScript(null, {file: "js/myscript.js"}, function(){
//all injected
});
});
}
//setup context menu
chrome.contextMenus.create({
"title" : "DESTROY!",
"type" : "normal",
"contexts" : ["page","selection","link","editable","image","video","audio"],
"onclick" : getClickHandler
});
i reference doingBrowserAction and contextTarg in myscript.js. I know what i'm trying to do is possible because the adblock extension does it, but having a hard time figuring out how. thanks in advance.
You cannot get a direct reference to a content script's DOM element from the background page, because the background page runs in the extension's process, and the content script runs in the tab's process. See also https://code.google.com/p/chromium/issues/detail?id=39507.
The document.activeElement property in the background page refers to the active element in the background page's document. As you can imagine, this value is quite useless.
If you query the state of the currently right-clicked element, bind an event in the content script. In the next example, I've chosen the contextmenu event, because context menus can also be opened through the keyboard.
This example adds a context menu option that removes the last active element from the document.
// content script
var lastElementContext;
document.addEventListener('contextmenu', function(event) {
lastElementContext = event.target;
}, true);
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (lastElementContext && lastElementContext.parentNode) {
lastElementContext.parentNode.removeChild(lastElementContext);
lastElementContext = null;
}
});
Background script:
chrome.contextMenus.create({
title: 'DESTROY!',
contexts: ['page', 'link', 'editable', 'image', 'video', 'audio'],
onclick: function(info, tab) {
chrome.tabs.sendMessage(tab.id, 'doDestroy');
}
});

JSON object does not update correctly

First of all, I'm not sure if my title describes the problem correctly... I did search but didn't find anything that helped me out...
The project I'm working on has an #orderList. All orders have a delete option. After an order gets deleted the list is updated.
Sounds simple... I ran into a problem though.
/**
* Data returned at the end of selecting some options
*/
$.post(myUrl, $('#myForm').serialize(), function(data) {
// I build the orderlist
// The data returned is a JSON object holding session data (including orders)
buildOrderList(data);
...
// Do some other work
});
/*
* function to build the html list
*/
function buildOrderList(data) {
// Empty list
$('#orderList').empty();
// The click handler for the delete button is in here because it needs the data object
$(document).on('click', '[id^=delete_]', function() {
// Get the orderId from the delete button
var orderId = $(this).attr('id').split('_');
orderId = orderId['1'];
// I call the delete function
deleteOrder(orderId, data);
});
var html = '';
// Loop the data object
$.each(data, function(key,val){
...
// Put html code needed in var html
...
});
$('#orderList').append(html);
}
/*
* function to delete an order
*/
function deleteOrder(orderId, data) {
// Because of it depends on other 'products' in the list if the user can
// simply delete it, I use a jQuery dialog to give him some options.
// These options I send to a php script so it knows what should be deleted.
// This fires when a user clicks on the 'delete' button from a dialog.
// The dialog uses data to show options but does not change the value of data.
switch(data.type) {
case 'A':
delMsg += '<p>Some message for case A</p>';
delMsg += '<select>with some options for case A</select>';
$('#wizard_dialog').append(delMsg);
$('#wizard_dialog').dialog('option', 'buttons', [
{ text: "Delete", click: function() {
$.post(myUrl, $('#myDeleteOptions').serialize(), function(newData) {
// Now the returned data is the updated session data
// So I build the orderList again...
buildOrderList(newData);
...
// Do some other work
});
$( this ).dialog( "close" );
$(this).html(''); }},
{ text: "Cancel", click: function() { $( this ).dialog("close"); $(this).html(''); }}
] );
break;
case 'B':
// Do the same thing but different text and <select> elements
break;
}
}
The orderList updates correctly, however if I try to delete another order, the jQuery dialog gives me the option for the current (correct product) AND the option for the product that previously owned the id of the current. (Hope I didn't loose anyone in my attempt to explain the problem)
The main question is how to 'refresh' the data send to buildOrderList.
Since I call the function in a new $.post with fresh data object returned it should work, shouldn't it?
/**
* Enable the JQuery dialog
* (#wizard_dialog)
* this is the init (note that I only open the dialog in deleteOrder() and set text and buttons according to the data send to deleteOrder() )
*/
$('#wizard_dialog').dialog({
autoOpen: false,
resizable: false,
modal: true,
dialogClass: "no-close",
open: function() {
$('.ui-dialog-buttonpane').find('button:contains("Annuleren")').addClass('cancelButtonClass');
$('.ui-dialog-buttonpane').find('button:contains("Verwijderen")').addClass('deleteButtonClass');
$('.ui-dialog :button').blur(); // Because it is dangerous to put focus on 'OK' button
$('.ui-widget-overlay').css('position', 'fixed'); // Fixing overlay (else in wrong position?)
if ($(document).height() > $(window).height()) {
var scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop(); // Works for Chrome, Firefox, IE...
$('html').addClass('noscroll').css('top',-scrollTop); // Prevent scroll without hiding the bar (thus preventing page to shift)
}
},
close: function() {
$('.ui-widget-overlay').css('position', 'absolute'); // Brake overlay again
var scrollTop = parseInt($('html').css('top'));
$('html').removeClass('noscroll'); // Allow scrolling again
$('html,body').scrollTop(-scrollTop);
$('#wizard_dialog').html('');
}
});
EDIT:
Because the problem could be in the dialog I added some code.
In the first code block I changed deleteOrder();
ANSWER
The solution was rather simple. I forgot to turn the click handler off before I added the new one. This returned the previous event and the new event.
$(document).off('click', '[id^=delete_]').on('click', '[id^=delete_]', function() {
// Get the orderId from the delete button
var orderId = $(this).attr('id').split('_');
orderId = orderId['1'];
// I call the delete function
deleteOrder(orderId, data);
});

jQuery UI Autocomplete - Building custom source

I have json array of the form:
[{"label":<some-label>,"spellings":[<list of spellings>]}, ...]
I need to parse the above array using jquery ui autocomplete. However, there are few constraints:
The autocomplete suggestions should involve matches from "spellings" but should suggest corresponding "label" only. e.g. if there are n "spellings" for a "label" then the autocomplete should show only that particular "label" for n "spellings".
On selecting from the suggestions provided, the corresponding "label" should only be reflected in the text input box.
How should I proceed with it? Any pointers?
And, how to iterate over list of "spellings" for a corresponding "label"?
This is what I'm trying to do, but giving garbled output.
var labels = []
var values = []
$.getJSON($url, function(data) {
$.each(data, function(key, val) {
for (var v in val.value)
values.push(val.value[v])
labels.push(val.label)
});
$("#text1").autocomplete({
minLength: 2,
source: values,
focus: function(event, ui) {
$("#text1").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#text1").val(ui.item.label);
return false;
}
});
});
I would build up a single source array of items, one for each spelling, where the label property is the label for each spelling and the value property is the spelling itself. This will enable you to quickly filter down results without having to iterate over each object's spelling array and check for matches which could take awhile.
Then, inside a function you define for source, you can do your own filtering logic, only allowing one instance of each "label" in the suggestions list.
Something like this should work (note that the autocomplete is initialized inside of the $.getJSON callback. This is necessary to make sure the source data is loaded before the widget is initialized):
$.getJSON($url, function(data) {
$.each(data, function (i, el) {
source.push({ label: el.label, value: el.label });
$.each(el.spellings, function (j, spelling) {
source.push({ label: el.label, value: spelling });
});
});
/* initialize the autocomplete widget: */
$("input").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i")
, results = [];
/* Make sure each entry is only in the suggestions list once: */
$.each(source, function (i, value) {
if (matcher.test(value.value) && $.inArray(value.label, results) < 0) {
results.push(value.label);
}
});
response(results);
}
});
});
Example: http://jsfiddle.net/MaMZt/

in mootools: calling a function after all events on an element is finished

i have this element to which various change events are applied
how can i trigger my own function after all change events have occurred in mootools
a sample scenario is a drop down list
$('ddl').addEvent('change', function () {
// some ajax call going on here and which i can't affect
// as the page is generated that way
});
i now want to call my function right after the change event is done but adding another change event will not do as i believe the events are executed async
pass on a callback function through the onComplete of the ajax that you reference.
eg:
$("ddl").addEvents({
change: function() {
new Request({
method: "get",
url: "somefile.php",
onComplete: function() {
// run your next stuff from within here, referencing
// this.response.text or whatevever and call up another function.
}
}).send("action=checkuser&id="+this.get("value").trim());
}
});
there's also the Chain class - http://mootools.net/docs/core/Class/Class.Extras#Chain but as you have async stuff going on, you really need the onComplete on the Request.