firefox extension button listener - firefox-addon

In my extension where the overlay.js comprises of the following events:
var sto =
{
onLoad: function() {...},
onMenuItemCommand: function(e) {...},
onToolbarButtonCommand: function(e) {...},
};
window.addEventListener("load", function () { sto.onLoad(); }, false);
I would need a listener fired every time a button is clicked in a loaded page. How can I achieve this?

Well I'm not sure if that's what u want but u can try to do an event delegation on the entire document:
var document_mouseup_lst = EventListener.createEventListener();
doc.addEventListener("mouseup", document_mouseup_lst, false);
document_mouseup_lst.addEvent("mouseup", function click(e, callback, object){
var element = e.target;
if(element.tagName.toLowerCase() === 'button') {
if (e.which == 1) { // left click
// do whatever u want
} else if (e.which == 2) { // middle click
// do whatever u want
}
}
return false;
});
btw in order to create the eventlistener (the EventListener object which got the createEventlistener method) I used this page Ajaxian >> An alternative way to addEventListener

I found the solution - was quite easy. Ok here is the source:
https://developer.mozilla.org/en/Code_snippets/Interaction_between_privileged_and_non-privileged_pages
and the modified code:
var sto =
{
onLoad: function() {...},
onMenuItemCommand: function(e) {...},
onMouseClick: function(e) {...},
onToolbarButtonCommand: function(e) {...},
};
window.addEventListener("load", function () { sto.onLoad(); }, false);
document.addEventListener("click", function(e) { sto.onMouseClick(e); }, false, true);

Related

why the function in side of function wont get called?

i have the following reactjs code to generate two dropdown list where the ddlproducts gets loaded by ddlCategories selection. but when i called the function getDataById() and tried to print the ajax populated array data2 to alert(), there was no alert() there were two alerts none of the alerts were prompted. it shown this error message on the IE console,
execution did not reached the function getDataById() 'cus the alert() in that function even didn't execute
SCRIPT438: Object doesn't support property or method 'getDataById'
correction: once the calling of this.props.getDataById() was changed to this.getDataById() it worked
but how do populate the ddlProducts dropdown. how do i access tag of the ddlProducts and then add the options to it?
here is the code:
var gdata=[];
var trStyle = {
'color': 'black',
'border-style' :'solid',
'margin-left':'20%'
};
var HCOMP = React.createClass({
getInitialState:function(){
return{data1:[], data2:[], isMounted:false, selectedValue:0}
},
componentDidMount:function(){
this.getData();
this.setState({isMounted:true})
},
ddlProdCatsChanegeEvent: function(e) {
if (this.state.isMounted)
{
var newV = ReactDOM.findDOMNode(this.refs.refProdCats).value;
var seleValue = newV;
this.setState({selectedValue:newV}, function(){
this.getDataById(this.state.selectedValue);
alert(this.state.data2);
});
}
},
render: function() {
var prodCats = this.state.data1.map(function(ele, index){// <PRODCATSOPTION optValue={ele.ProductCategoryID} optText={ele.Name} />
return <option value={ele.ProductCategoryID} data-key={index}>{ele.Name}</option>
});
prodCats.unshift(<option value={''}>{'---- select category ------'}</option>)
return (<div>Prodcut Category:<br /><select id="ddlCategories" ref="refProdCats" onChange={this.ddlProdCatsChanegeEvent}>{prodCats}</select><br />
Products:<br /><select id="ddlPorducts" ref="refProds"></select><br /></div>
)
},
getDataById:function(catId){
var x = catId;
alert('rec id:'+x);
$.ajax({
url:'http://localhost:53721//Home/GetProductCats?id='+ x,
method:'GET',
success:function(d1){
this.setState({data2:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
},
getData:function(){
//ajax here
$.ajax({
url:'http://localhost:53721//Home/GetProductCats',
method:'GET',
success:function(d1){
this.setState({data1:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
}
});
var PRODOPTIONS = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
var PRODCATSOPTION = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
ReactDOM.render( <HCOMP/>, document.getElementById('d1') );
Try updating ddlProdCatsChanegeEvent to ddlPropCatsChangeEvent.

Firefox addon progress listener

I am using this page to implement an address bar change listener.
https://developer.mozilla.org/en-US/docs/Code_snippets/Progress_Listeners#Example.3a_Notification_when_the_value_in_Address_Bar_changes
This code does what it is supposed to do. When I navigate to a new page, it alerts the URL. However, if the URL I have is 302 or similar it causes an issue. It will alert the redirected URL and not the original URL. I need the URL before the request is sent to the server and the redirect happens. Is this possible?
I think you can check this via the onStateChange event.
var myExtension = {
oldURL: null,
init: function() {
gBrowser.addProgressListener(this);
},
uninit: function() {
gBrowser.removeProgressListener(this);
},
processNewURL: function() {},
// nsIWebProgressListener
QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
onLocationChange: function(aProgress, aRequest, aURI) {
this.processNewURL(aURI);
},
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
if (!aRequest) return;
if (aStateFlags & nsIWebProgressListener.STATE_START) {
alert(aRequest.name);
},
onProgressChange: function() {},
onStatusChange: function() {},
onSecurityChange: function() {}
};
window.addEventListener("load", function() { myExtension.init() }, false);
window.addEventListener("unload", function() { myExtension.uninit() }, false);
See more here: https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIRequest
aRequest is a nsIRequest, whose property name is the URL of the request.

Change zIndex in HighChart

using Highchart, how can we change the zIndex for a line according to its state, or dynamically from a click event ?
I tried :
plotOptions: {
series: {
states: {
select: {
lineWidth: 2,
zIndex:10
}
},
with : this.setState(this.state === 'select' ? '' : 'select'); in the Click event but it doesn't work.
Alright, it's definitely not pretty, but I couldn't find a way to actually set the zIndex, so I had to do some maneuvering to fake it and bring each series to the front in a certain order. Here's the snippet to include:
Highcharts.Series.prototype.setState = (function (func) {
return function () {
if (arguments.length>0){
if (arguments[0] !== ''){
if (typeof this.options.states[arguments[0]]['zIndex'] !== 'undefined'){
this.options.oldZIndex = this.group.zIndex;
this.group.zIndex = this.options.states[arguments[0]]['zIndex'];
}
}else{
if (typeof this.options['oldZIndex'] !== "undefined"){
this.group.zIndex = this.options['oldZIndex'];
}
}
var order = [], i = 0;
$.each(this.chart.series, function(){
order.push({id:i,zIndex:this.group.zIndex,me:this});
i++;
});
order.sort(function(a,b){return (a.zIndex>b.zIndex) ? 1 : -1;});
$.each(order, function(){
this.me.group.toFront();
});
func.apply(this, arguments);
}
};
} (Highcharts.Series.prototype.setState));
And here's the JSFiddle demonstrating:
http://jsfiddle.net/G9d9H/9/
Let me know if that's what you needed.
I think a better solution is to set the series.group.toFront() method on click (I prefer to use it on mouseover)
plotOptions: {
series: {
events: {
click: function () {
this.group.toFront();//bring series to front when hovered over
}
}
}
}

events not firing when creating single instance of a view, but works when mutliple instance are created

I'm a complete newbie to Backbone and am trying to get my head round few things. Im trying to build something using jQuery mobile and Backbone. Please find my code below
var WelcomePage = Backbone.View.extend({
initialize:function () {
this.template = _.template($("#welcome_template").html());
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events:{
"click .btn_continue" : function(){
appRouter.navigate('login',{trigger: true});
}
}
});
var Login = Backbone.View.extend({
initialize:function () {
this.template = _.template($("#login_template").html());
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events:{
"click .btn_login" : function(){
appRouter.navigate('dashboard',{trigger: true});
}
}
});
var Dashboard = Backbone.View.extend({
initialize:function () {
this.template = _.template($("#dashboard_template").html());
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events:{
"click .btn_loadImages" : function(){
console.log('load Images');
}
}
});
var Router = Backbone.Router.extend({
routes:{
"":"welcome",
"login":"login",
"dashboard":"dashboard",
},
initialize:function () {
},
welcome:function () {
this.changePage(new WelcomePage());
},
login:function () {
this.changePage(new Login());
},
dashboard:function(){
this.changePage(new Dashboard());
},
changePage:function (page) {
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
$.mobile.changePage($(page.el), {changeHash:false, transition: 'slide'});
}
});
var appRouter = new Router();
Backbone.history.start();
Now while I go back and forth through the screens using the BACK key the events fire OK using the code above. Then I tried replacing the code for the Router with the code below
var Router = Backbone.Router.extend({
routes:{
"":"welcome",
"login":"login",
"dashboard":"dashboard",
},
initialize:function () {
},
welcome:function () {
this.changePage(v_WelcomePage);
},
login:function () {
this.changePage(v_Login);
},
dashboard:function(){
this.changePage(v_Dashboard);
},
changePage:function (page) {
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
$.mobile.changePage($(page.el), {changeHash:false, transition: 'slide'});
}
});
var v_WelcomePage = new WelcomePage();
var v_Login = new Login();
var v_Dashboard = new Dashboard();
var appRouter = new Router();
Backbone.history.start();
I noticed when I go back to the previous screens the events stop firing. Instead of creating the instance of the view in the action of the router I have created it outside and call it each time.I hope im making some sense.
Any advice much appreciated.
Events are hooked up using jQuery when the view is instantiated, not rendered (in the Backbone View constructor function). jQuery disconnects those events when the html is removed from the page (probably in $.mobile.changePage).
So, the second time you render the page, the events will not be hooked back up. You could try calling page.delegateEvents() to manually hook up the events again, or you could re-create the view each time.

TipTip only working on second hover after ajaxpost

Situation:
My tooltips show up on my page. Opening my fancybox works. Doing the ajax post from that fancybox works.
But my tooltips don't work in that fancybox. And they don't work after my ajax post.
I tried to reinitialize TipTip with the callbacks of fancybox.
EDIT
Title changes
So I found a way to let it run on the second hover after post but not on first hover.
I also found some explanations here but it still didn't fix my problem. Probably doing it wrong.
EDIT 2
Tootip in fancybox working use afterShow only.
Changes
added this in $(function () { so that it calls this function instead of initTipTip.
$(".tooltip").live('mouseover', function () {
$(this).tipTip();
});
Code of my function that does the post thing and closes my fancybox.
var reservation = MakeReservation();
var oldDateSplit = $("#resDate").val().split('/');
var newDateSplit = $("#dateEditReservation").val().split('/');
var oldDate = new Date(oldDateSplit[2], oldDateSplit[1] - 1, oldDateSplit[0]);
var newDate = new Date(newDateSplit[2], newDateSplit[1] - 1, newDateSplit[0]);
var time = $("#txtTime");
$.ajax({
url: ResolveUrl('~/Reservation/CheckSettings'),
data: "JSONString=" + reservation + "&hasJavaScriptMethod=" + true
}).done(function (data) {
if (data.length == 0 || oldDate.getTime() == newDate.getTime()) {
$.fancybox.close();
var id = $("#reservationId").val();
$("#reservationList").load(ResolveUrl('~/Reservation/reservationList',
function () { initTipTip(); }));
$("#reservationDetail").load(ResolveUrl('~/Reservation/DetailInfo',
function () { initTipTip(); }), { reservationId: id });
$("#reservationList").on("hover", " .tooltip", function () { $(this).tipTip(); });
}
else {
$(".errorDiv").removeClass("hidden");
$(".errorDiv").html(data);
$(".btnReservations").removeAttr('disabled');
}
});
NEW
$(".tooltip").live('mouseover', function () {
$(this).tipTip();
});
}
Still the same as before the edit.
Code initialization for TipTip
function initTipTip () {
$(".tooltip").tipTip();
}
Code of fancybox
function openFancy() {
$("a.inline").fancybox({
'type': 'ajax',
'afterShow': function () {
return initTipTip();
}
});
$("a.inlineBlockedDate").fancybox({
'type': 'ajax',
'ajax': { cache: false },
'afterShow': function () {
return initTipTip();
}
});
}
I found the solution for this.
So I used my .live in $(function(){ like in my question but I did not use ".tooltip" here but the table itself. I also use initTipTip here instead of $(this).tipTip();
So this solves the Tooltip from TipTip.
Explanation: This is because the tooltip.live only gets triggered on first hover and not when the table 'refreshes'. So now you add that event on that refresh of the table
Correct me if I'm wrong here.
So no need for any other .tiptip stuff or InitTipTip then in $(function(){
$("#reservationList").live('mouseover', function () {
initTipTip();
});
I hope your problem gets solved with this question.

Resources