How to run js function on element that appears dynamically with Ember? - javascript

I'm working on an Ember project and I have a button that inserts some HTML tags into the DOM. I want to call a javascript function to run upon loading of those new DOM elements. Here's my code:
<script type="text/x-handlebars" id="doc">
{{#if isEditing}}
{{partial 'doc/editbox'}}
{{/if}}
...
</script>
The partial doc/editbox simply contains some html tags.
I've tried running the javascript as part of the click button event that initiate the insertion, but the js doesn't work because the DOM elements don't exist yet. I saw this post:
How to Run Some JS on an Element in the Index Template in Ember.js RC2
which suggested using Ember.run.next, however that didn't work since the View 'Doc' originally appears without those additional DOM elements (until button is clicked). How do I get the javascript function to run at the correct time?

add an observes in the controller
watchEditing: function(){
if (this.get('isEditing')){
Ember.run.scheduleOnce('afterRender', function(){
//do it here
});
}
}.observes('isEditing')
additionally you could use render instead of partial and create an associated view, and run it in the didInsertElement of that view.

Related

Best practice to set up JavaScript event handlers for partial views

I have a partial view that is loaded via JQuery ajax. It enumerates through properties in the Model and renders HTML elements which need JavaScript events bound.
Here is some simplified razor code I have now
foreach(MyObject item Model.MyObjectList)
{
string containerId = "Container" + item.Id;
string onMouseOut = "DoSomething('"+containerId+"',#Model.Id)";
<div id="#containerId" onmouseout="#onMouseOut">
//Other code here
</div>
}
This works OK however it is often said to be better to bind events in JQuery, if I did this you could also utilise JQuery events such as "onmouseleave".
So another method I could do is place a script block inside each enumeration which sets up the events like so
<script type='text/javascript'>
$('##containerId').mouseout(function(){
DoSomething('#containerId',#Model.Id)
});
</script>
However this results in lots of script block being rendered.
Is there another better solution for setting up events in partial views?
Use the .on method to bind events to things that will not always be inside the DOM.
$('#foo').on('click', function() {
// do stuff
});
You then remove the need to insert script tags in your partials. There was a method similar to this that was .live() but has since been deprecated in v1.7 and removed since v1.9.
jQuery API : .on();

EmberJS - Handling events for multiple elements inside a view

I have a Handlebars template called 'projects' and a view called 'ProjectsView' which references the template with the templateName property.
This projects template generates a list of divs from a model and each div needs to be expanded on a click.
{{#each project in model}}
<div class="project">
<img src="{{project.logo}}" /> <!-- Execute a different logic for the click event -->
<h4>{{project.title}}</h4> <!-- Execute a different logic for this click
{{/each}}
I initially used the action helper and added a relevant method inside the actions hash of the ProjectsController. However, the action is being executed on all the divs in the list instead of just the clicked one.
Previous versions of Ember used to provide a context argument for the action but it is no longer the case. It turns out the recommended way to handle DOM events is within in the view like below.
App.ProjectsView = Ember.View.extend({
templateName: 'projects',
click: function(event) {
// Do something with the event
}
})
However, it doesn't feel right to write a bunch of if's inside the click handler to find if the click event was triggered on an image or a h4 and act accordingly. Is this is the right way of handling events or am I doing it wrong?
You can instead use App.ProjectsView as a CollectionView with each project as it's child view.
App.ProjectsView = Ember.View.extend({
templateName: 'projects',
itemViewClass: 'App.ProjectView'
})
You can handle actions in your child views directly using the target=view option in action helper.
Since you want to do DOM related tasks (expand/collapse), handling the actions in the views will help as you can get a jQuery object of the view using this.$().

Meteor/Handlebars jQuery Updating DOM

Using jQuery and Meteor I am trying to bind the TokenInput plugin to the DOM like so:
$(function(){
console.log("binding tokeninput");
$(".nameInput").tokenInput(friendsList.data)
});
The issue is that the particular DOM element is being redrawn (removed from the DOM and then re-added in a quick flash) occasionally. I need to ensure that the plugin is ALWAYS in effect on that input.
A few things come to mind:
Could I use a callback from Meteor to re-apply it whenever it updates? I haven't found a callback from Meteor for when a template object is refreshed.
Can I use some sort of reactive bind (like .on, though .on is only for events)?
Am I doing this completely wrong?
If you're DOM element being removed by something reactive. If mytiem changes its going to fire the 'rendered' template callback
e.g
<template name="MeteorIsAwesome">
{{#each myitem}}
<div class="dom element meteor">
</div>
{{/each}}
{{!comment - you can put it here or above}}
<input class="nameInput" type="text">
</template>
Js (kind of the callback you might be looking for)
Template.MeteorIsAwesome.rendered = function () {
$(".nameInput").tokenInput(friendsList.data)
}
One thing only worries me is if it ignores the state of the tokenbox when redrawing so it might become double tokenized

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

JQuery - Appended Links don't work

I have created a dynamic list picker script using Jquery 1.3 and PHP that sends a JSON AJAX request and returns a list of items to choose from. The AJAX call works perfectly returning an array of items that I use Jquery to append them as an unordered list to an empty container DIV. That portion of the process works as expected.
The problem comes from the fact that from that list of items, I'm drawing them as links whose clicks are handled by a rel attribute. Here's an example:
<a rel="itemPick" id="5|2" href="#">This is the link</a>
The JQUERY handler looks like:
$('a[rel=itemPick]').click(function () {
code here...
});
These links and click handlers work fine when the page loads, but when they are appended to the container DIV, the click event does not get picked up. I don't want to have to refresh the entire HTML page again, so is there something I need to do in addition to append() to get JQUERY to recognize the newly added links?
When you use the jQuery.click method, it's looking for all of the "a" elements that currently exist on the page. Then, when you add a new "a" element, it has no knowledge of that click event handler.
So, there's a new event model in jQuery that allows you to bind functions to all current and future elements called Live Events. You can use Live Events the same way that you use normal event binding, but they will work for all future elements specified. So, you can simply switch your binding logic to:
$('a[rel=itemPick]').live('click', function () {
//code here...
})
$('a[rel=itemPick]').live("click", function (){ code here... });
Do you bind the event after adding the links?

Categories