Yahoo UI Custom Button - button

I have a YUI button defined through HTML markup. I managed to get it loaded and "skinned" properly.
The problem is a custom click event. I have tried a number of approaches all of which links the custom function to the 'click' event, but no matter which way I do it, it ALWAYS triggers upon page loading and then it doesn't fire when clicked. I can't seem to get it to "wait" for a user to click. It just shoots like a virgin on his first date.
Code below....
<script type="text/javascript">
YAHOO.util.Event.onContentReady("submitbutton", onButtonReadySubmit);
YAHOO.util.Event.onContentReady("editbutton",onButtonReadyEdit);
var myTabs = new YAHOO.widget.TabView("demo");
function editDoc(sBaseRef, sUNID) {
var sNewURL = sBaseRef + "/0/" + sUNID + "?EditDocument";
alert("Going to : " + sNewURL);
window.location.href=sNewURL;
}
function onButtonReadySubmit() {
var oSubmitButton = new YAHOO.widget.Button("submitbutton");
}
function onButtonReadyEdit() {
var oEditButton = new YAHOO.widget.Button("editbutton");
YAHOO.util.Event.addListener("editbutton", 'click', editDoc('a URL path goes here' , 'A PageKey goes here'));
}

YUI Button publishes its own click event that you subscribe to on the YUI Button instance, rather than using YAHOO.util.Event.addListener. This is described in detail on the YUI Button landing page: http://developer.yahoo.com/yui/button/#handlingevents.

Your problem is the 3rd argument. That should be a reference to function. What happens in your code is that the 3 argument is a function that is called as the listener is being created, and returns nothing.
You have:
YAHOO.util.Event.addListener("editbutton", 'click', editDoc(
'a URL path goes here',
'A PageKey goes here'
));
Simply what you want is:
YAHOO.util.Event.addListener("editbutton", 'click', editDoc);
However, you also want to pass 'a URL path goes here' and 'A PageKey goes here' to the function at click-time. To do this, use the optional fourth argument to addListener() - an object to pass to the function.
function editDoc (ev, oArgs) {
var sBaseRef = oArgs.url,
sUNID = oArgs.key;
/* code here */
}
YAHOO.util.Event.addListener("editbutton", 'click', editDoc, {
url: 'a URL path goes here',
key: 'A PageKey goes here'
});
See http://developer.yahoo.com/yui/docs/YAHOO.util.Event.html#method_addListener for more.
As Todd mentions, you can also do this as part of the YUI Button creation - but the same issues of function versus function references apply.

Related

How to hook into the "close infobubble" event in HERE maps Javascript API

I can create infobubbles using the HERE maps Javascript API - eg from their documentation:
function addInfoBubble(map) {
map.set('center', new nokia.maps.geo.Coordinate(53.430, -2.961));
map.setZoomLevel(7);
var infoBubbles = new nokia.maps.map.component.InfoBubbles(),
TOUCH = nokia.maps.dom.Page.browser.touch,
CLICK = TOUCH ? 'tap' : 'click',
container = new nokia.maps.map.Container();
container.addListener(CLICK, function (evt) {
infoBubbles.openBubble(evt.target.html, evt.target.coordinate);
}, false);
map.components.add(infoBubbles);
map.objects.add(container);
addMarkerToContainer(container, [53.439, -2.221],
'<div><a href=\'http://www.mcfc.co.uk\' >Manchester City</a>' +
'</div><div >City of Manchester Stadium<br>Capacity: 48,000</div>');
addMarkerToContainer(container, [53.430, -2.961],
'<div ><a href=\'http://www.liverpoolfc.tv\' >Liverpool</a>' +
'</div><div >Anfield<br>Capacity: 45,362</div>');
}
function addMarkerToContainer(container, coordinate, html) {
var marker = new nokia.maps.map.StandardMarker(
coordinate,
{html: html}
);
container.objects.add(marker);
}
I would like to hook into the close event of the infobubble. I realise I could use jQuery to find the span that contains the close button (examining the markup, I believe it has the class nm_bubble_control_close) and do something when this is clicked. However I thought there would be a built-in event that I could use.
Does anyone know if there is a built-in event that fires when the infobubble is closed? I can't find anything in the documentation.
The InfoBubbles component has a property "openBubbleHandles". It's an OList you can observe to see when bubbles are opened (i.e. added to the list) or closed (removed from the list).
AFAIK there is no built-in event, there's also no related property which may be observed.
Possible workaround:
override the built-in close-method with a custom function:
container.addListener(CLICK, function (evt) {
var b = infoBubbles.openBubble(evt.target.html, evt.target.coordinate),
c = b.close;
b.close = function(){
//do what you want to
alert('bubble will be closed');
//execute the original close-method
c.apply(b)
}
}, false);
For the current HERE Javascript API version (3.x) the working solution can be found here:
HERE Maps - Infobubble close event / hook

Meteor controlling copying and pasting in a text field

I am trying to prevent copying and pasting white spaces in the username field inside my Meteor app template but I am always getting an error as shown below, can someone please tell me what I am doing wrong / missing and is there any other way to control content pasted in a text field in Meteor template? Thanks
Template.UserRegisteration.events({
'input #username':function(e,t){
this.value = this.value.replace(/\s/g,'');
}
});
Error:
Uncaught TypeError: Cannot read property 'replace' of undefined
this is the context is the data context where the input id="username field is.
To get the field's DOM element use e.currentTarget instead of this.
As Akshat mentioned to get field DOM element use e.currentTarget instead of this, back to your question code sample please try the following
Template.UserRegisteration.events({
'input #username':function(e,t){
var text = e.currentTarget.value;
e.currentTarget.value = text.replace(/\s/g,'');
}
});
The following example sets out how to extract and set the value of a DOM element within a Meteor event:
https://www.meteor.com/try/4
Template.body.events({
"submit .new-task": function (event) {
// This function is called when the new task form is submitted
var text = event.target.text.value;
Tasks.insert({
text: text,
createdAt: new Date() // current time
});
// Clear form
event.target.text.value = "";
// Prevent default form submit
return false;
}
});
Within a Meteor events block, "this" is not the DOM element so you cannot call a value on it.

Framework7 starter page "pageInit" NOT WORKING

anyone using framework7 to create mobile website? I found it was great and tried to learn it by myself, now I meet this problem, after I create my App, I want to do something on the starter page initialization, here, my starter page is index.html, and I set data-page="index", now I write this below:
$$(document).on('pageInit', function (e) {
var page = e.detail.page;
// in my browser console, no "index page" logged
if (page.name === 'index') {
console.log("index page");
});
// but I changed to any other page other than index, it works
// my browser logged "another page"
if(page.name === 'login') {
console.log('another page');
}
});
Anyone can help? Thank you so much.
I have also encountered with the same problem before.
PageInit event doesn't work for initial page, only for pages that you navigate to, it will only work for index page if you navigate to some other page and then go back to index page.
So I see two options here:
Just not use pageInit event for index page - make its initialization just once (just make sure you put this javascript after all its html is ready, or e.g. use jquery's on document ready event)
Leave index page empty initially and load it dynamically via Framework7's mainView.loadContent method, then pageInit event would work for it (that was a good option for me as I had different index page each time, and I already loaded all other pages dynamically from underscore templates)
I am facing same issue and tried all solutions in various forums.. nothing actually worked. But after lot of RnD i stumbled upon following solution ...
var $$ = Dom7;
$$(document).on('page:init', function (e) {
if(e.detail.page.name === "index"){
//do whatever.. remember "page" is now e.detail.page..
$$(e.detail.page.container).find('#latest').html("my html here..");
}
});
var me = new Framework7({material: true});
var mainview = me.addView('.view-main', {});
.... and whatever else JS here..
this works perfectly..
surprisingly you can use "me" before initializing it..
for using for first page u better use document ready event. and for reloading page event you better use Reinit event.
if jquery has used.
$(document).on('ready', function (e) {
// ... mainView.activePage.name = "index"
});
$(document).on('pageReinit', function (e) {
//... this event occur on reloading anypage.
});

Bootboxjs: how to render a Meteor template as dialog body

I have the following template:
<template name="modalTest">
{{session "modalTestNumber"}} <button id="modalTestIncrement">Increment</button>
</template>
That session helper simply is a go-between with the Session object. I have that modalTestNumber initialized to 0.
I want this template to be rendered, with all of it's reactivity, into a bootbox modal dialog. I have the following event handler declared for this template:
Template.modalTest.events({
'click #modalTestIncrement': function(e, t) {
console.log('click');
Session.set('modalTestNumber', Session.get('modalTestNumber') + 1);
}
});
Here are all of the things I have tried, and what they result in:
bootbox.dialog({
message: Template.modalTest()
});
This renders the template, which appears more or less like 0 Increment (in a button). However, when I change the Session variable from the console, it doesn't change, and the event handler isn't called when I click the button (the console.log doesn't even happen).
message: Meteor.render(Template.modalTest())
message: Meteor.render(function() { return Template.modalTest(); })
These both do exactly the same thing as the Template call by itself.
message: new Handlebars.SafeString(Template.modalTest())
This just renders the modal body as empty. The modal still pops up though.
message: Meteor.render(new Handlebars.SafeString(Template.modalTest()))
Exactly the same as the Template and pure Meteor.render calls; the template is there, but it has no reactivity or event response.
Is it maybe that I'm using this less packaging of bootstrap rather than a standard package?
How can I get this to render in appropriately reactive Meteor style?
Hacking into Bootbox?
I just tried hacked into the bootbox.js file itself to see if I could take over. I changed things so that at the bootbox.dialog({}) layer I would simply pass the name of the Template I wanted rendered:
// in bootbox.js::exports.dialog
console.log(options.message); // I'm passing the template name now, so this yields 'modalTest'
body.find(".bootbox-body").html(Meteor.render(Template[options.message]));
body.find(".bootbox-body").html(Meteor.render(function() { return Template[options.message](); }));
These two different versions (don't worry they're two different attempts, not at the same time) these both render the template non-reactively, just like they did before.
Will hacking into bootbox make any difference?
Thanks in advance!
I am giving an answer working with the current 0.9.3.1 version of Meteor.
If you want to render a template and keep reactivity, you have to :
Render template in a parent node
Have the parent already in the DOM
So this very short function is the answer to do that :
renderTmp = function (template, data) {
var node = document.createElement("div");
document.body.appendChild(node);
UI.renderWithData(template, data, node);
return node;
};
In your case, you would do :
bootbox.dialog({
message: renderTmp(Template.modalTest)
});
Answer for Meteor 1.0+:
Use Blaze.render or Blaze.renderWithData to render the template into the bootbox dialog after the bootbox dialog has been created.
function openMyDialog(fs){ // this can be tied to an event handler in another template
<! do some stuff here, like setting the data context !>
bootbox.dialog({
title: 'This will populate with content from the "myDialog" template',
message: "<div id='dialogNode'></div>",
buttons: {
do: {
label: "ok",
className: "btn btn-primary",
callback: function() {
<! take some actions !>
}
}
}
});
Blaze.render(Template.myDialog,$("#dialogNode")[0]);
};
This assumes you have a template defined:
<template name="myDialog">
Content for my dialog box
</template>
Template.myDialog is created for every template you're using.
$("#dialogNode")[0] selects the DOM node you setup in
message: "<div id='dialogNode'></div>"
Alternatively you can leave message blank and use $(".bootbox-body") to select the parent node.
As you can imagine, this also allows you to change the message section of a bootbox dialog dynamically.
Using the latest version of Meteor, here is a simple way to render a doc into a bootbox
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,MyCollection.findOne({_id}),box.find(".modal-body")[0]);
If you want the dialog to be reactive use
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,function() {return MyCollection.findOne({_id})},box.find(".modal-body")[0]);
In order to render Meteor templates programmatically while retaining their reactivity you'll want to use Meteor.render(). They address this issue in their docs under templates.
So for your handlers, etc. to work you'd use:
bootbox.dialog({
message: Meteor.render(function() { return Template.modalTest(); })
});
This was a major gotcha for me too!
I see that you were really close with the Meteor.render()'s. Let me know if it still doesn't work.
This works for Meteor 1.1.0.2
Assuming we have a template called changePassword that has two fields named oldPassword and newPassword, here's some code to pop up a dialog box using the template and then get the results.
bootbox.dialog({
title: 'Change Password',
message: '<span/>', // Message can't be empty, but we're going to replace the contents
buttons: {
success: {
label: 'Change',
className: 'btn-primary',
callback: function(event) {
var oldPassword = this.find('input[name=oldPassword]').val();
var newPassword = this.find('input[name=newPassword]').val();
console.log("Change password from " + oldPassword + " to " + newPassword);
return false; // Close the dialog
}
},
'Cancel': {
className: 'btn-default'
}
}
});
// .bootbox-body is the parent of the span, so we can replace the contents
// with our template
// Using UI.renderWithData means we can pass data in to the template too.
UI.insert(UI.renderWithData(Template.changePassword, {
name: "Harry"
}), $('.bootbox-body')[0]);

How does google analytics track events when user navigates to other page inside one domain

In Google's documentation it is said that an event can be tracked in the following way:
<a onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);">click me</a>
or older version:
<a onclick="pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);">click me</a>
I was looking with Firebug to the request that are made when a click on a link and I see there aborted request:
http://www.google-analytics.com/__utm.gif?utmwv=4.7.2&utmn=907737223&....
This happens because browser unload all javascript when user navigates to a new page. How in this case event tracking is performed?
Edit:
Since one picture can be worth a thousand words...
When I click a link firebug shows me this sequence of requests (here are shown first four, after follows requests to fill page content)
The problem is that there isn't enough time for the script to finish running before the user is taken to the next page. What you can do is create a wrapper function for your GA code and in the onclick, call the wrapper function and after the GA code is triggered in your wrapper function, set a time out and update location.href with the link's url. Example:
click me
<script type='text/javascript'>
function wrapper_function(that,category,action,opt_label,opt_value) {
_gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
window.setTimeout("window.location.href='" + that.href + "'", 1000);
}
</script>
code will vary a bit based on your link but hopefully you get the idea - basically it waits a little bit before taking the user to the target url to give the script some time to execute.
Update:
This answer was posted several years ago and quite a lot has happened since then, yet I continue to get feedback (and upvotes) occasionally, so I thought I'd update this answer with new info. This answer is still doable but if you are using Universal Analytics then there is a hitCallback function available. The hitCallback function is also available to their traditional _gaq (ga.js) but it's not officially documented.
This problem is answered in Google's documentation:
use
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
or
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var pageTracker=_gat._getTracker("UA-XXXXX-X");
pageTracker._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
This more or less the same as the answer from Crayon Violet, but has a nicer method name and is the official solution recommended by Google.
As above, this is due to the page being unloaded prior to the Async call returning. If you want to implement a small delay to allow gaq to sync, I would suggest the following:
First add a link and add an extra class or data attribute:
My Link
Then add into your Javascript:
$("a[data-track-exit]").on('click', function(e) {
e.preventDefault();
var thatEl = $(this);
thatEl.unbind(e.type, arguments.callee);
_gaq.push( [ "_trackEvent", action, e.type, 'label', 1 ] );
setTimeout(function() {
thatEl.trigger(event);
}, 200);
});
I don't really condone this behavior (e.g. if you are going to another page on your site, try to capture the data on that page), but it is a decent stop-gap. This can be extrapolated not just for click events, but also form submits and anything else that would also cause a page unload. Hope this helps!
I had the same issue. Try this one, it works for me. Looks like that ga doesnt like numbers as a label value. So, convert it to string.
trackEvent: function(category, action, opt_label, opt_value){
if(typeof opt_label === 'undefined') opt_label = '';
if(typeof opt_value === 'undefined') opt_value = 1;
_gaq.push([
'_trackEvent',
String(category),
String(action),
String(opt_label),
opt_value
]);
}

Resources