I'm trying to draw in a canvas created in a Mithril's component. My problem is that I don't want this component's view to be redrawn when the application needs. I found that the onremove/oncreate methods are calling each time a redraw is launched. Does Mithril recreate my canvas each time the application is redrawn ? Is there a solution to avoid that because I can't call createPlot() each time the application need a redraw... ?
My code :
export default function ResultsLinePlot(state){
return {
onremove: function() {
},
oncreate: function(){
if(_filter(state)){
createPlot() // ChartJS draw the plot in the canvas "ChartLinePlot"
}
},
view : function(){
return _filter(state) ? m('div', {class: 'row'}, [
(state.results.length > 0) ? m('div', {class: 'col-md-12'},[
m('canvas',{id:"chartLinePlot",width:"400",height:"400"})
]) : null
]) : null
}
}
}
Related
Some features in my component turn on or off depend on browser size, therefore I want to check browser width on resize event. However, I could do it using OnInit method. But I need to refresh browser when resize happened to update browser width
ngOnInit() {
if (window.innerWidth <= 767){
---- do something
}
}
I tried to use OnChanges method, but it does not work either.
OnChanges(changes:SimpleChanges){
console.log( 'width:====>' + changes[window.innerWidth].currentValue);
if ( changes[window.innerWidth].currentValue <= 767 ){
---- do something
}
}
is there any suggestions or alternative way to accomplish this?
You could just put handler on resize event over window object, but this will allow you to put only single resize event, latest registered event on onresize will work.
constructor(private ngZone:NgZone) {
window.onresize = (e) =>
{
//ngZone.run will help to run change detection
this.ngZone.run(() => {
console.log("Width: " + window.innerWidth);
console.log("Height: " + window.innerHeight);
});
};
}
To make it more angular way use #HostListener('window:resize') inside your component, which will allow to call your resize function(on which HostListner decorator has been mount) on resize of window.
#HostListener('window:resize', ['$event'])
onResize(event){
console.log("Width: " + event.target.innerWidth);
}
Use HostListener. You should probably debounce the resize event though before doing anything, it will fire everytime the size changes which could be dozens or hundreds of times in a few milliseconds as the user drags the window size.
import { Component, HostListener } from '#angular/core';
#Component({...})
class TestComponent {
#HostListener('window:resize')
onWindowResize() {
//debounce resize, wait for resize to finish before doing stuff
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}
this.resizeTimeout = setTimeout((() => {
console.log('Resize complete');
}).bind(this), 500);
}
}
An easier way would be using the resize method on the html block that you want to detect:
<div class="some-class" (window:resize)="onResize($event)">...</div>
Then in your .ts file you can just add:
onResize(event) {
const innerWidth = event.target.innerWidth;
console.log(innerWidth);
if (innerWidth <= 767) {
...do something
}
}
Add this outside of the ngOnInit() {} unless you wanted the window size on page load.
When you resize your window, you'll see the console.log
In the following code, I have a view which extends from another view (but does not inherit any functionality, only renders the template) and a model which I want to implement now. My view is for a like button, which I need to retrieve the state of the like button from the server each time the page is loaded. I am not sure how to do this using the model. Do I need to have an Ajax call in the model retrieving the state from the server or does that call fall into the view?
This is my code:
var likeButton = Backbone.Model.extend ({
initialize: function () {
this.isLiked = /* need something here! Ajax call to get state of button from server? */
}
});
var LikeButtonView = BaseButtonView.extend({ // extends form a previews view which simply extends from backbone and render's the template
template: _.template($('#like-button').html()),
sPaper: null,
sPolyFill: null,
sPolyEmpty: null,
isLiked: false,
events: {
"click .icon": "like",
},
model: new likeButton (),
initialize: function (options) {
BaseButtonView.prototype.initialize.apply(this, [options]); // inherit from BaseButtonView
this.likeButn = $("button.icon", this.$el);
this.svgNode = this.likeButn.find("svg").get(0); // find the svg in the likeButn and get its first object
this.sPaper = Snap(this.svgNode); // pass in the svg object into Snap.js
this.sPolyFill = this.sPaper.select('.symbol-solid');
this.sPolyEmpty = this.sPaper.select('.symbol-empty');
if (this.model.isLiked) {
this.likeButn.addClass("liked");
} else if (!this.model.isLiked) {
this.likeButn.addClass("unliked");
}
},
like: function() {
this._update();
},
_update: function () {
if ( !this.isLiked ) { // if isLiked is false, remove class, add class and set isLiked to true, then animate svg to liked position
this._like();
} else if ( this.isLiked ) { // is isLiked is false, remove class, add class, set isLiked to false, then animate svg to unliked position
this._unlike();
}
},
_like: function() {
this.likeButn.removeClass("unliked");
this.likeButn.addClass("liked");
this.isLiked = true;
this.sPolyFill.animate({ transform: 't9,0' }, 300, mina.easeinout);
this.sPolyEmpty.animate({ transform: 't-9,0' }, 300, mina.easeinout);
},
_unlike: function() {
this.likeButn.removeClass("liked");
this.likeButn.addClass("unliked");
this.isLiked = false;
this.sPolyFill.animate({ transform: 't0,0'}, 300, mina.easeinout);
this.sPolyEmpty.animate({ transform: 't0,0' }, 300, mina.easeinout);
}
});
There are three ways to implement the 'like' button's knowledge of the current state of the page: A hidden field delivered from the HTML, an Ajax call to the server, or generating your javascript server-side with the state of the like model already active.
Let's start with the basics. Your code is a bit of a mess. A model contains the state of your application, and a view is nothing more than a way of showing that state, receiving a message when the state changes to update the show, and sending messages to the model to change the state. The model and the view communicate via Backbone.Events, and the view and the DOM communicate via jQuery.Events. You have to learn to keep those two separate in your mind.
Here, I've turned your "like" model into an actual model, so that the Backbone.Event hub can see the changes you make.
var likeButton = Backbone.Model.extend ({
defaults: {
'liked': false
}
});
Now in your view, the initial render will draw the state in gets from the model. When a DOM event (described in the 'events' object) happens, your job is to translate that into a state change on the model, so my "toggleLike" only changes the model, not the view. However, when the model changes (explicitly, when the "liked" field of the model changes), the view will then update itself automatically.
That's what makes Backbone so cool. It's the way views automatically reflect the reality of your models. You only have to get the model right, and the view works. You coordinate the way the view reflects the model in your initialization code, where it's small and easy to reason about what events from the model you care about.
var LikeButtonView = BaseButtonView.extend({
template: _.template($('#like-button').html()),
events: {
"click .icon": "toggleLike",
},
initialize: function (options) {
BaseButtonView.prototype.initialize.call(this, options); // inherit from BaseButtonView
// A shortcut that does the same thing.
this.likeButn = this.$("button.icon");
this.model.on('change:liked', this._updateView, this);
},
render: function() {
BaseButtonView.prototype.render.call(this);
// Don't mess with the HTML until after it's rendered.
this.likeButn.addClass(this.model.isLiked ? "liked", "unliked");
},
toggleLike: function() {
this.model.set('liked', !this.model.get('liked'));
},
_updateView: function () {
if (this.model.get('liked')) {
this._showLikedState();
} else {
this._showUnlikedState();
}
}
});
How the like model gets initialized is, as I said above, up to you. You can set a URL on the model's options and in your page's startup code tell it to "fetch", in which case it'll get the state from some REST endpoint on your server. Or you can set it to a default of 'false'. Or you can set it in hidden HTML (a hidden div or something) and then use your page startup code to find it:
new LikeButtonView({model: new LikeButton({}, {url: "/where/page/state/is"}));
or
new LikeButtonView({model: new LikeButton({liked: $('#hiddendiv').data('liked')}, {}));
If you're going to save the liked state, I'd recommend the URL. Then you have someplace to save your data.
//load up profile controller.
function go_to_profile() {
var controller = Alloy.createController('Profile', {
title : 'Profile',
name : '_profile',
isFlyout : true
});
var newWindow = controller.getView();
Alloy.Globals.navGroup.openWindow(newWindow, {
animated : true,
transition:Titanium.UI.iPhone.AnimationStyle.CURL_UP
});
}
Here is my code. I would like to modify it, so that the window slides in upwards. The transition does not seem to work and keeps sliding in from left to right.
Any idea why, cheers.
It's simple, the Ti.UI.iOS.NavigationWindow doesn't allow the transitions.
Only when you call `Window.open()' you can define a transition prop.
I am wanting to use Collapsible DIVs to show and hide content from the user.
I found this jQuery code to do the expand and collapse:
http://webcloud.se/code/jQuery-Collapse/
However the content is already loaded in the divs (its just hidden from view).
So I then found this:
http://www.raymondcamden.com/index.cfm/2011/4/5/Collapsible-content-and-Ajax-loading-with-jQuery-Mobile
Which loads the content into the opening div but also unloads it when it closes!
However its all mixed in with jQuery mobile and so it styled.
I want to be able to style the divs myself. also the first example uses nice bounce or fade effects to bring the content into view.
The reason for doing this is I want to show the user different content such as images or flash files but I don't want everything to load into the page on page load, this would be too much stuff.
So how can I use the first jQuery Collapse example but with loading external pages in?
I liked the question so I spent a little time making something close to a plugin:
//only run the event handler for collapsible widgets with the "data-url" attribute
$(document).delegate('.ui-collapsible[data-url] > .ui-collapsible-heading', 'click', function () {
//cache the collapsible content area for later use
var $this = $(this).siblings('.ui-collapsible-content');
//check if this widget has been initialized yet
if (typeof $this.data('state') === 'undefined') {
//initialize this widget
//update icon to gear to show loading (best icon in the set...)
$this.siblings('.ui-collapsible-heading').find('.ui-icon').removeClass('ui-icon-plus').addClass('ui-icon-gear')
//create AJAX request for data, in this case I'm using JSONP for cross-domain abilities
$.ajax({
//use the URL specified as a data-attribute on the widget
url : $this.closest('.ui-collapsible').data('url'),
type : 'get',
dataType : 'jsonp',
success : function (response) {
//get the height of the new content so we can animate it into view later
var $testEle = $('<div style="position:absolute;left:-9999px;">' + response.copy + '</div>');
$('body').append($testEle);
var calcHeight = $testEle.height();
//remove the test element
$testEle.remove();
//get data to store for this widget, also set state
$this.data({
state : 'expanded',
height : calcHeight,
paddingTop : 10,
paddingBottom : 10
//add the new content to the widget and update it's css to get ready for being animated into view
}).html('<p>' + response.copy + '</p>').css({
height : 0,
opacity : 0,
paddingTop : 0,
paddingBottom : 0,
overflow : 'hidden',
display : 'block'
//now animate the new content into view
}).animate({
height : calcHeight,
opacity : 1,
paddingTop : $this.data('paddingTop'),
paddingBottom : $this.data('paddingBottom')
}, 500);
//re-update icon to minus
$this.siblings('.ui-collapsible-heading').find('.ui-icon').addClass('ui-icon-minus').removeClass('ui-icon-gear')
},
//don't forget to handle errors, in this case I'm just outputting the textual message that jQuery outputs for AJAX errors
error : function (a, b, c) { console.log(b); }
});
} else {
//the widget has already been initialized, so now decide whether to open or close it
if ($this.data('state') === 'expanded') {
//update state and animate out of view
$this.data('state', 'collapsed').animate({
height : 0,
opacity : 0,
paddingTop : 0,
paddingBottom : 0
}, 500);
} else {
//update state and animate into view
$this.data('state', 'expanded').animate({
height : $this.data('height'),
opacity : 1,
paddingTop : $this.data('paddingTop'),
paddingBottom : $this.data('paddingBottom')
}, 500);
}
}
//always return false to handle opening/closing the widget by ourselves
return false;
});
The collapsible HTML looks like this:
<div data-role="collapsible" data-url="http://www.my-domain.com/jsonp.php">
<h3>Click Me</h3>
<p></p>
</div>
Here is a demo: http://jsfiddle.net/YQ43B/6/
Note that for the demo I found the best way to make the initial animation smooth was to add this CSS:
.ui-mobile .ui-page .ui-collapsible .ui-collapsible-content {
padding-top : 0;
padding-bottom : 0;
}
The default padding added by jQuery Mobile is 10px for both top and bottom paddings, I added those values as data-attributes to each widget to maintain the defaults.
Note that this code can be slightly tweaked to show other types of content, I used JSONP simply because you can use it on JSFiddle.
Here is an example that I made :
$(document).ready(function () {
$('.accordian_body').hide();
});
$('.accordian_head').click(function () {
$(this).next().animate(
{ 'height': 'toggle' }, 'fast'
);
Then in HTML
<div class="accordian_head"></div>
<div class="accordian_body"></div>
in CSS you can style the head and body however you like , to add in code behind -
<asp:Literal ID="lit1" runat="server" />
foreach(DataRow dr in DataTable.Rows)
{
lit1.Text = lit1.Text + "<div class=\"accordian_head\">" Whatever you want... "</div><div class=\"accordian_body\">" Whatever in body "</div>
}
Check this link it's in php and shows how to load external link to DIV Ajax can load only internal pages and doesn't work across domains.
I have an element controlling the rendering of a child element. (A TouchableHighlight that sets some state in its onPress.) In the child element's componentDidMount method I construct an Animated.spring and start it. This works for entry, but I need to do the same animation in reverse to exit (it's like a drawer). componentWillUnmount executes too quickly for Animated.spring to even start working.
How would I handle animating the child's exit?
I have implemented a FadeInOut component that will animate a component in or out when its isVisible property changes. I made it because I wanted to avoid explicitly handling the visibility state in the components that should enter/exit with an animation.
<FadeInOut isVisible={this.state.someBooleanProperty} style={styles.someStyle}>
<Text>Something...</Text>
</FadeInOut>
This implementation uses a delayed fade, because I use it for showing progress indicator, but you can change it to use any animation you want, or generalise it to accept the animation parameters as props:
'use strict';
import React from 'react-native';
const {
View,
Animated,
PropTypes
} = React;
export default React.createClass({
displayName: 'FadeInOut',
propTypes: {
isVisible: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
style: View.propTypes.style
},
getInitialState() {
return {
view: this.props.children,
opacity: new Animated.Value(this.props.isVisible ? 1 : 0)
};
},
componentWillReceiveProps(nextProps) {
const isVisible = this.props.isVisible;
const shouldBeVisible = nextProps.isVisible;
if (isVisible && !shouldBeVisible) {
Animated.timing(this.state.opacity, {
toValue: 0,
delay: 500,
duration: 200
}).start(this.removeView);
}
if (!isVisible && shouldBeVisible) {
this.insertView();
Animated.timing(this.state.opacity, {
toValue: 1,
delay: 500,
duration: 200
}).start();
}
},
insertView() {
this.setState({
view: this.props.children
});
},
removeView() {
this.setState({
view: null
});
},
render() {
return (
<Animated.View
pointerEvents={this.props.isVisible ? 'auto' : 'none'}
style={[this.props.style, {opacity: this.state.opacity}]}>
{this.state.view}
</Animated.View>
);
}
});
I think you have the animation ownership inverted. If you move your animation logic to the parent that is opening and closing the child, the problem becomes much simpler. Rather than beginning the animation on componentDidMount, do it on the click of your TouchableHighlight in addition to, but independent of, whatever prop manipulations on the child you need to do.
Then when the user clicks to close, you can simply reverse the animation as per normal and you don't really even need to unload it. Also this would allow you to have a reusable drawer (the thing that slides up and down) and it's abstracted away from the content within it. So you can have a single drawer mechanism supporting multiple different types of content.