Ember and window load hook - javascript

What hook can I use in ember that will only run after all of the content has been loaded?
I'm using zurb foundation's top-bar fixed and once a view is rendered I want to do something like this to dynamically space my body:
$(window).load(function() {
$("body").css("padding-top", parseInt($(".top-bar").css("height")) - 2);
});
The closest solution I've found here is:
Ember.View.reopen({
didInsertElement : function(){
this._super();
Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
},
afterRenderEvent : function(){
// implement this hook in your own subclasses and run your jQuery logic there
}
});
This almost works except for the fact that all of the content is not yet loaded i.e. images have not yet been loaded and therefore calculation above is wrong.

Inside the afterRenderEvent you can use some jQuery logic that waits for the image to be fully loaded
afterRenderEvent : function(){
$(photo).bind('load',doSomething());
}

Related

Ember - Resize DIV on load, transition and resize?

I'm building an Ember app that needs to size a container DIV to be full window height on load of the application, and then run the same resize function again when transitioning to a new route, and then also on window resize.
On a normal site, I'd do this:
var appUI = {
init: function(){
appUI.sizeContainer();
},
sizeContainer: function(){
var winHeight = jQuery(window).height();
jQuery('#container').height(winHeight);
},
onResize: function() {
appUI.sizeContainer();
}
}
jQuery(document).ready(function($){
appUI.init();
jQuery(window).resize(function(){
appUI.onResize();
});
});
But obviously this won't work in Ember.
This can't be a component, because the #container DIV wraps the entire current view. But with Ember moving away from views, how should I do this?
The only way I came up with was to use a view, and hook onto didInsertElement, but I couldn't figure out how can I do it without having to create a view.js file for every route, that contains the same resize code? And how about the resize event? I thought the application view didInsertElement might work for this, but it only runs once on load.
All my route templates basically follow this patten:
{{top-header}}
{{background-image image=backgroundImage}}
{{side-menu session=session menuOpen=menuOpen}}
<div id="container" class="vert-center route-name">
{{partial "_logo"}}
{{some-component}}
</div>
On loading the application and on window resize can be done pretty much the way you described.
One easy way is to override the renderTemplate hook inside the ApplicationRoute. Within this hook, you can render your application template and then initialize the resize listener on the window object:
// handles on document load and on window change events
App.ApplicationRoute = Ember.Route.extend({
renderTemplate: function(controller, model) {
this.render('application'); // render the application template
appUI.init(); // call the init event on application load
Ember.$(window).resize(function() { // setup resize listener on the window object that will be called when window resizes
appUI.onResize();
});
}
});
As far as resizing each time a route loads, you could implement a generic Ember.Route, let's call it ResizableRoute for example, that calls the appUI.resize() after its template is rendered. This can again be achieved with overriding the renderTemplate hook.
// calls onResize() each time the current route's template is rendered in the DOM
App.ResizableRoute = Ember.Route.extend({
renderTemplate: function() {
// render the template with the same name as the route (assumes you follow ember naming conventions)
this.render(this.routeName);
// call resize since the route is loaded
appUI.onResize();
}
});
Now you can make any other route extend this ResizableRoute and, every time that route's template is rendered, appUI.onResize() will be called.
App.AnyOtherRoute = App.ResizableRoute.extend({
// do other stuff
});
The reason all the calls are made AFTER the template is rendered is because that way the #container element is definitely inserted in the DOM already and can be grabbed using jQuery.
Here is a running jsFiddle example
EDIT
Instead of overriding the renderTemplate hook, another way you could achieve this is to create a ResizeUIComponent that will perform resizing each time your route is loaded. The flaw is that you have to remember to insert this component into each route's template.
App.ResizeUIComponent = Ember.Component.extend({
didInsertElement: function() {
this.$().hide(); // make the component invisible, probably better to do it with css but this is a quick example
appUI.onResize();
}
});
And add this component to all templates (including application) you want to call onResize() each time they load:
{{top-header}}
{{background-image image=backgroundImage}}
{{side-menu session=session menuOpen=menuOpen}}
<div id="container" class="vert-center route-name">
{{resize-ui}} {{!-- add the invisible resize component as the child of #container to ensure necessary rendering order --}}
{{partial "_logo"}}
{{some-component}}
</div>
And you can add a listener on the window object after the init event of the ApplicationController:
App.ApplicationController = Ember.Controller.extend({
onInit: function() {
Ember.$(window).resize(function() { // setup resize listener on the window object that will be called when window resizes
appUI.onResize();
});
}.on('init');
});

Link to leanModal.js works fine in rendered by HTML link but not within React

I am using Lean Modal: http://leanmodal.finelysliced.com.au/ in a Rails app with a React front-end.
When I put the link to the modal in application.html.erb it works fine but when loaded through a React link using the same code, nothing happens.
I have jQuery loaded and checked 10 times if the code is the same. What could cause such an issue?
Here is the link code in React:
<a rel="leanModal" name="login" href="#login">
The template file (html.erb) script:
<script type="text/javascript">
$(function() {
$('a[rel*=leanModal]').leanModal({ top : 200, closeButton: ".modal_close" });
});
And I am loading the modal JS from my application.js file in Rails.
Thanks for any help!
You should wrap things that interact with DOM (e.g. jQuery plugins) in a component.
var LeanModal = React.createClass({
componentDidMount: function(){
$(this.getDOMNode()).leanModal({
top: this.props.top || 200
});
},
render: function(){
return <div>{this.props.children}</div>;
}
});
Note that you also need to provide a componentWillUnmount to handle clean up, and that the plugin can't do things like add/remove elements. Plugins that don't allow cleanup or make destructive changes are incompatible with react.
Sometimes implementing it with just the existing CSS and using react components instead of the jQuery plugin can be very simple and end up with a better result.

Load jQuery after ExtJS

Disclaimer: ExtJS - intermediate level;
jQuery - beginner
I've looked for a solution for this but had not found anything yet.
I have both ExtJS and jQuery in one file and I want to be able to execute the jQuery right after the ExtJS is done building a page (is this even possible).
Example:
function renderPage(){
// ExtJS goes here
}
How do I call jQuery after renderPage() is completed?
I tried the following:
$(document).ready(function() {
$("tr").css("background-color", "yellow");
});
$(document).ready(function(renderPage) {
$("tr").css("background-color", "yellow");
});
function renderPage(){
// ExtJS goes here
// ...
$("tr").css("background-color", "yellow");
}
but it doesn't work. I assume it is because the ExtJS is not done rendering the page when jQuery is getting called and it is not finding anything to select.
Additional information:
I know my jQuery works and is connected to the library because I was able to select HTML elements that are rendered before any script ExtJS or jQuery script is run and modify their style.
Thanks!
Ext components fire an afterrender event that you can hook into, but you have to be careful here because it can fire more than once if you render more than once (which is easy to do accidentally). This is an example of a simple app that fires afterrender once for a panel.
Ext.application({
name : 'Fiddle',
launch : function() {
var panel = Ext.create('Ext.Panel',{
renderTo:Ext.getBody(),
title:'myPanel',
items: [
Ext.create('Ext.Button', {
text: 'Click me!!!!',
handler: function() {
alert('You clicked the button!');
}
}),
{
xtype:'toolbar',
items: [{text:'Button 1'}, {text:'Button 2'}],
listeners: {
afterrender: function () {
Ext.Msg.alert('Fiddle', 'done with ext rendering, do jQuery stuff');
}
}
}
]
});
}
});
sencha fiddle: https://fiddle.sencha.com/#fiddle/eqg
I would recommend not mixing these two libraries without a really good reason - Ext has virtually the same DOM helper functionality as jQuery - if you are just changing a class something like Ext.dom.Element.addCls might be more appropriate (http://docs-origin.sencha.com/extjs/4.2.2/#!/api/Ext.dom.Element)

jQuery - bxSlider plugin reloadSlider issues

I'm using jQuery with the bxSlider plugin, here is the link to it just incase: http://bxslider.com/
I'm trying to reload the slider and my custom pager after I've removed certain slides from it.
Here is what I have tried:
$(function() {
var slider = $('#slider').bxSlider({
pagerCustom: '#bx-pager'
});
$('.list').on('click', '.delete', function() {
image = $(this).closest('li').find('[type="hidden"]');
// image.attr('id') contains a string: image-0, image-1, image-2, etc.
$('#slider, #bx-pager').find('.' + image.attr('id')).remove();
slider.reloadSlider({
pagerCustom: '#bx-pager'
}); // I have also tried: slider.reloadSlider();
});
});
It works partially. What happens is the slider gets reloaded just fine but it removes the pager completely when it runs the reload.
Thank you very much for any help.
As long as I see, this is a bug in bxSlider, in fact, when you call the reloadSlider method, internally are called the methods destroySlider and init.
In the destroySlider method the pagerEl element is destroyed, this is right if you are not using a custom one, because it is recreated programmatically in the init method, but if you are using a custom one it can't be recreated programmatically.
I ended up modifying the destroySlider method to check if a custom pager is used, in this case it must not be deleted.
Here is the before (line 1294):
if(slider.pagerEl) slider.pagerEl.remove();
And after:
if (slider.settings.pagerCustom === '') {
if(slider.pagerEl) slider.pagerEl.remove();
}
I'll post the bug on GitHub as soon as I have the time.

Loading data ajax style

I jsut started learning angular.js. Can you guys show me the right way to make a page that initially presents an ajax loader element saying 'Loading data' or something like that. Then after data's been fetched it would update the view and hide the element. I can put stuff in page load event using jquery, but how do you do that using pure angular? So far I figured out how to put that in click event:
<div ng-app="VideoStatus" ng-controller="VideoStatusCtrl">
<button ng-click="getVideos()">get videos</button>
</div>
<script type="text/javascript">
angular.module('VideoStatus', ['ngResource']).run(function(){
// I guess somehow I can start fetching data from the server here,
// but I don't know how to call Controller methods passing the right scope
});
function VideoStatusCtrl($scope, $resource) {
$scope.videoStatus = $resource('/Videos/GetStatuses', { callback: 'JSON_CALLBACK' });
$scope.getVideos = function () {
$scope.videoResult = $scope.videoStatus.get();
console.log('videos fetched');
};
};
</script>
Kudos to Adam Webber & Peter Bacon Darwin
Here is the working plunker
Here is my version plunker that make loading as a directive with modal popup feature
Here is the tutorial to use my version
you only need loading.js and modal.js and reference jQuery and twitterbootstrap css.
in your code,
Only 2 steps you need to do with your code.
Add the following code to HTML
< div data-loading> < /div>
Add LoadingModule module to your application module.
angular.module('YourApp', ['LoadingModule'])

Categories

Resources