Register new event listeners in Polymer 1.0 after initial page load - dom

In my Polymer 1.0 app, I have an on-tap function which dynamically adds another button into the page based on a few parameters in the form. The problem is that after adding the element and its event listener to the page, the new button won't actually fire the on-tap event.
JSFiddle for testing: https://jsfiddle.net/dme6tb7z/
index.html
<template is="dom-bind" id="app">
<div id="output"></div>
<paper-button id="myButton" on-tap="_addButton">Add Button</paper-button>
</template>
<script src="app.js"></script>
Here is where I create the new button and give it a listener in JS. Is there some kind of extra step I need to take so that Polymer can "see" the new on-tap event listener?
app.js
app._addButton = function(e) {
var el = document.createElement('paper-button');
el.innerHTML = "New Button";
el.id = "newbutton";
el.addEventListener('on-tap', '_testEvent');
this.$.output.appendChild(el);
// I also tried adding the event listener after appending
// the element to the page, like so...
// this.$.newButton.addEventListener('on-tap', '_testEvent');
};
app._testEvent = function(e) {
console.log(e);
};
EDIT
I'm thinking maybe I need to use something like Polymer.dom(parent).appendChild(node) to keep the two DOMs in sync. I did this in my app.js like so, but the event still doesn't fire.
app.js scope
(function(document) {
'use strict';
var app = document.querySelector('#app');
...
app._addButton = function(e) {
var el = document.createElement('paper-button');
el.innerHTML = "New Button";
el.id = "newbutton";
el.addEventListener('on-tap', '_testEvent');
var parentNode = document.getElementById('output');
Polymer.dom(parentNode).appendChild(el);
};
...
})(document);
Surely, there must be some way to add event listeners after initial page load? I've done this same thing countless times in other setups, but there's something weird going on with Polymer... I understand there are two DOMs to update, but I'm using the Polymer.dom method, so what in the world is preventing this from happening?
More Info
I noticed that after appending the new button to the page, I can successfully run this:
document.getElementById('newbutton').innerHTML = 'Hello World';
whereas this:
document.getElementById('newbutton').addEventListener('on-tap', '_testEvent');
has no effect (and no errors). Isn't that bizarre? Is there some sort of reinvented registration process in Polymer to add event listeners?

Okay, I think I figured it out.
First of all, on-tap in this context should be tap.
Second, the function name from JS should be formatted like this: this.functionName, or app.functionName if your template has an id of "app" and app is defined as var app = document.querySelector('#app');
All together, it looks like this:
var newElement = document.getElementById('newbutton');
newElement.addEventListener('tap', this._testEvent );
This doesn't work in the JS Fiddle for some reason, but does work in a real Polymer environment.

Related

Leaflet - How to add click event to button inside marker pop up in ionic app?

I am trying to add a click listener to a button in a leaftlet popup in my ionic app.
Here I am creating the map & displaying markers, also the method I want called when the header tag is clicked is also below:
makeCapitalMarkers(map: L.map): void {
let eventHandlerAssigned = false;
this.http.get(this.capitals).subscribe((res: any) => {
for (const c of res.features) {
const lat = c.geometry.coordinates[0];
const lon = c.geometry.coordinates[1];
let marker = L.marker([lon, lat]).bindPopup(`
<h4 class="link">Click me!</h4>
`);
marker.addTo(map);
}
});
map.on('popupopen', function () {
console.log('Popup Open')
if (!eventHandlerAssigned && document.querySelector('.link')) {
console.log('Inside if')
const link = document.querySelector('.link')
link.addEventListener('click', this.buttonClicked())
eventHandlerAssigned = true
}
})
}
buttonClicked(event) {
console.log('EXECUTED');
}
When I click this header, Popup Open & Inside if are printed in the console, so I know I'm getting inside the If statement, but for some reason the buttonClicked() function isn't being executed.
Can someone please tell me why this is the current behaviour?
I just ran into this issue like 2 hours ago. I'm not familiar with ionic, but hopefully this will help.
Create a variable that keeps track of whether or not the content of your popup has an event handler attached to it already. Then you can add an event listener to the map to listen for a popup to open with map.on('popupopen', function(){}). When that happens, the DOM content in the popup is rendered and available to grab with a querySelector or getElementById. So you can target that, and add an event listener to it. You'll have to also create an event for map.on('popupclose', () => {}), and inside that, remove the event listener from the dom node that you had attached it to.
You'd need to do this for every unique popup you create whose content you want to add an event listener to. But perhaps you can build a function that will do that for you. Here's an example:
const someMarker = L.marker(map.getCenter()).bindPopup(`
<h4 class="norwayLink">To Norway!</h4>
`)
someMarker.addTo(map)
function flyToNorway(){
map.flyTo([
47.57652571374621,
-27.333984375
],3,{animate: true, duration: 5})
someMarker.closePopup()
}
let eventHandlerAssigned = false
map.on('popupopen', function(){
if (!eventHandlerAssigned && document.querySelector('.norwayLink')){
const link = document.querySelector('.norwayLink')
link.addEventListener('click', flyToNorway)
eventHandlerAssigned = true
}
})
map.on('popupclose', function(){
document.querySelector('.norwayLink').removeEventListener('click', flyToNorway)
eventHandlerAssigned = false
})
This is how I targeted the popup content and added a link to it in the demo for my plugin.
So yes you can't do (click) event binding by just adding static HTML. One way to achieve what you want can be by adding listeners after this new dom element is added, see pseudo-code below:
makeCapitalMarkers(map: L.map): void {
marker.bindPopup(this.popUpService.makeCapitalPopup(c));
marker.addTo(map);
addListener();
}
makeCapitalPopup(data: any): string {
return `` +
`<div>Name: John</div>` +
`<div>Address: 5 ....</div>` +
`<br/><button id="myButton" type="button" class="btn btn-primary" >Click me!</button>`
}
addListener() {
document.getElementById('myButton').addEventListener('click', onClickMethod
}
Ideally with Angular, we should not directly be working with DOM, so if this approach above works you can refactor adding event listener via Renderer.
Also I am not familiar with Leaflet library - but for the above approach to work you need to account for any async methods (if any), so that you were calling getElementById only after such DOM element was successfully added to the DOM.

DOM elements not accessible after onsen pageinit in ons.ready

I am using the Onsen framework with jQuery and jQuery mobile, it appears that there is no way to catch the event that fires once the new page is loaded.
My current code, which executes in the index.html file (the master page)
<script src="scripts/jQuery.js"></script>
<script src="scripts/jquery.mobile.custom.min.js"></script>
<script src="scripts/app.js"></script>
<script>
ons.bootstrap();
ons.ready(function() {
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
});
in app.js is the following code
function initRecentPage() {
$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
ons.compile(content);
}
and the HTML:
<ons-page id="recentPage">
<ons-toolbar id="myToolbar">
<div id="toolBarTitle" class="center">Recent Checks</div>
<div class="right">
<ons-toolbar-button ng-click="mySlidingMenu.toggleMenu()">
<ons-icon icon="bars"></ons-icon>
</ons-toolbar-button>
</div>
</ons-toolbar>
<ons-scroller>
<h3 class="headingTitle"> Checks</h3>
<div id="Free" class="tabArea">
<ons-list id="yourReports">
</ons-list>
<ons-button id="clearFreeRecentButton">
<span id="clearRecentText" class="bold">Clear Recent Checks</span>
</ons-button>
</div>
</ons-scroller>
</ons-page>
in this instance the variable 'content' is always null. I've debuged significantly, and the element I am trying to get is not present when this event fires. It is loaded later.
So, the question is, how do I ensure that all of the content is present before using a selector. It feels like this is an onsen specific issue.
In the end I could only find one reliable way of making this work.
Essentially I had to wait, using setTimeout 300 milliseconds for the DOM elements to be ready. It feels like a hack, but honestly there is no other reliable way of making this behave. The app is in the app store and works well, so even though it seems like a hack, it works:
$(document).on('pageinit', '#homePage', function() {
initHomePage();
});
function initHomePage() {
setTimeout(function() {
setUpHomePage();
}, 300);
}
Move your $(document.body).on('pageinit', '#recentPage', function() { outside of ons.ready block.
JS
ons.bootstrap();
ons.ready(function() {
console.log("ready");
});
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
function initRecentPage() {
//$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
alert(content)
ons.compile(content);
}
I commented out a line because I do not have access to that "recentShowReport"
You can see how it works here: 'http://codepen.io/vnguyen972/pen/xCqDe'
The alert will show that 'content' is not NULL.
Hope this helps.

trigger iframe onload event when doing an ajax replacement on content within the iframe

I have a view with a credit card payment form hosted on Domain A. Domain B has a seperate website with an iframe to the credit card form on domain A.
The form on domain A uses an ajax form like this:
<% using (Ajax.BeginForm("CreditCard", "Framed", new { id = Model.SID },
new AjaxOptions()
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "credit-card-wrapper",
LoadingElementId = "loading-pane"
},
new { id = "new-creditcard-form" }))
{ %>
Then on domain b, I am using a custom jquery plugin to manage my iframe by allowing external events to change the src of the iframe. The usage looks like this
$('#myIframe').frameplugin('creditcard');
Which causes the iframe to change it's src to the credit card page. I also have attached an onload to the iframe like this:
$(this).bind('load', function () {
var src = $(this).attr('src').toLowerCase();
//do stuff based on url
});
What I want to do is when the credit card form is submitted and the replacement is done, I want the document within the iframe to trigger the iframe's onload event, so that domain b knows something happened.
Another solution would be to somehow bind custom events to the iframe and trigger them within the framed document. I'm not sure how/if that would even work. Any ideas?
EDIT:
I am attempting to use an event trigger from the iframe up to the parent and I get an error.
Unsafe JavaScript attempt to access
frame with URL
http://localhost:59905/Home/Framed
from frame with URL
http://localhost:27412/Framed/Index/.
Domains, protocols and ports must
match.
Here's my event binding
$(document).bind('success:myframe', function (event, referenceId) {
//do something
});
and here's the javascript call from the framed page. This is called from OnSuccess in the ajax.beginform
function paymentReceived() {
var referenceNumber = $('#referenceNumber').text();
$(top.document).trigger('success:myframe', referenceNumber);
}
I think you just want to pass events from iFrame to the parent window. Please correct me if I'm wrong.
From your iFrame, can't you just do this?
$(document).ready(function() {
parent.alertPageWithIFrameThatLoadIsComplete();
});
Edit:
Let me try again.
This works for me:
<script type="text/javascript">
function oniframeLoad() {
alert("Loaded!");
}
function changePage() {
frames["my_iframe"].location.href = "http://google.com";
}
setTimeout(changePage, 2000);
</script>
<iframe onload="oniframeLoad()" name="my_iframe" id="my_iframe" src=""></iframe>

Preventing HTTP REQUEST on javascript DOM update

I am getting re-execution of imported js files upon a hitting a form button which calls a function to insert a DOM element into page ( in simulation to exe of an ajx callback function). The DOM insertion causes a page refresh which re-requests all files from server.
Nothing big on the function call:
var addFashionVideo = function() {
var nodeContainer = document.getElementById('vidList');
var mytitle = document.forms.addVideo.newVidName.value;
var addTextNode = document.createTextNode(mytitle);
var newLI = document.createElement('LI');
newLI.appendChild(addTextNode);
nodeContainer.appendChild(newLI);
return this;
};
TARGET DIV for DOM update code is :
<div id="ajParent" class="aj" style="width:325px;background-color:blue;color:white;">
<ul id="vidList">
<li>Watch Fashion Paris Video</li>
</ul>
</div>
I place an alert on this page and after the function attempts to insert the new LI
[ oddly the LI appears for a split second then disappears ] a page refresh is triggered
and my alert on the page re-executes.
// Perhaps Maybe I have a browser issue on this computer or I am just to new of a scripter
// to not see the problem...any comment appreciated.
The minute you hit submit on a form, the page will reload since you have made a GET request with the form. In order to stop the form from submitting you would have to make it return false on submit. e.g.
document.getElementById('formname').onsubmit = function {
return false;
};
You would have to make sure to disable form submission so the page doesn't reload, then you could run your ajax request on submission and do what you must on success in the ajax function.
I really doubt your dom insertion is causing the reload.

Popup browser back to parent browser after a certain page is reached

I have a popup (which I used by necessity) that is opened on a link click. I have the user going through a series of pages picking attributes to then be sent to a shopping cart.
My problem: After the user reaches the end of the selection process i want to kill the open popup and send the request back to the original browser (parent) so the user can checkout.
Any idea how I would do this?
Javascript: in the child (popup) window.
window.opener.location = 'page.html";
window.close();
Is that what your looking for?
The parent window can be accessed using "opener" in JavaScript.
Example:
window.opener.title='hello parent window';
or
window.opener.location.href='http://redirect.address';
Script in my child form:
<script language="JavaScript" type="text/javascript">
function SetData() {
// form validation
// var frmvalidator = new Validator("myForm");
// frmvalidator.addValidation("name","req","Please enter Account Name");
// get the new dialog values
var str1 = document.getElementById("name").value;
var winArgs = str1;
// pass the values back as arguments
window.returnValue = winArgs;
window.close();
document.myForm.submit();
}
</script>
Script in my parent form:
<% #account_head= current_company.account_heads.find_by_name("Sundry Debtors")%>
<script type="text/javascript">
function OpenDialog() {
var winSettings = 'center:yes;resizable:no;help:yes;status:no;dialogWidth:450px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('<%= "/accounts/new?account_head_id=#{#account_head.id} #man" %>', winSettings);
if(winArgs == null) {
window.alert("no data returned!");
} else {
// set the values from what's returned
document.getElementById("to_account_auto_complete").value = winArgs;
}
}
</script>
This is work but not as i want, any one if found good solution please suggest.