What's the best way with Famous to implement these well known mobile app design patterns?
!) "hamburger" and side-menu like this jasny example ?
2 )Table-View, transitioning to full-screen details page, a little like:
http://goratchet.com/examples/app-movies/
Thanks!
You should be aware that the famo.us university timbre menu lesson is now available. Here is a version I did long before that came out. It is more of the one file here are the critical issues implementations than the 27 class version. Following this I did eventually produce an abstraction of the menu into a generalized tool. There is actually very little difference between the menu below and a standard (one level deep) menu with the exception of what transitions you use. Here is a drag-to-uncover menu. You could of course trigger the open and/or close with a click as well... you can also see the code and play it live at codefamo.us.
/*globals define*/
define(function(require, exports, module) {
'use strict';
// import dependencies
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Easing = require('famous/transitions/Easing');
var ContainerSurface = require('famous/surfaces/ContainerSurface');
var EventHandler = require('famous/core/EventHandler');
var MouseSync = require('famous/inputs/MouseSync');
var TouchSync = require('famous/inputs/TouchSync');
var Draggable = require('famous/modifiers/Draggable');
var mainContext = Engine.createContext();
// Content Page...
var coverState = true;
var coverPos = 0;
//var coverMod = new StateModifier();
var coverDrag = new Draggable({
projection: 'x'
});
var coverSurface = new Surface({
size:[undefined,undefined],
content:'click to open',
properties:{
color:'white',
backgroundColor:'#44f',
zIndex:'3'
}
});
//mainContext.add(coverMod).add(coverDrag).add(coverSurface);
mainContext.add(coverDrag).add(coverSurface);
coverDrag.activate();
function coverReset() {
coverDrag.setPosition([0,0],
{ duration : 100, curve: 'easeInOut' },
function() {
coverSurface.setContent('drag to open');
coverPos = 0;
}
);
coverState = true;
}
function coverDrawOut() {
coverDrag.setPosition([200,0],
{ duration : 600, curve: 'easeInOut' },
function() {
coverSurface.setContent('drag to close');
coverPos = 200;
}
);
coverState=false;
}
coverDrag.on('update',function(data) {
//console.log(data);
if(data.position[0]>60) {
menuFadeIn();
}
});
coverDrag.on('end',function(data) {
if(data.position[0]<100) {
coverReset();
menuFadeOut();
}else {
coverDrawOut();
menuFadeIn();
}
});
coverSurface.pipe(coverDrag);
// Menu Items...
var todaysSpecials = ['pizza','hamburger','french fries','ice cream'];
var itemSurfs = [];
var itemMod1 = [];
var itemMod2 = [];
// Create menu item surfaces, modifiers, etc.
for (var i=0;i<todaysSpecials.length;i++) {
itemSurfs[i] = new Surface({
size: [150, 30],
content: '<span class="entypo">☰</span>'+todaysSpecials[i],
properties: {
color: 'white',
textAlign: 'center',
backgroundColor: '#FA5C4F',
zIndex:'1'
}
});
itemSurfs[i].menuData = {
id:i,
text: todaysSpecials[i]
};
//console.log(itemSurfs[i]);
itemMod1[i] = new StateModifier();
itemMod2[i] = new StateModifier();
mainContext.add(itemMod1[i]).add(itemMod2[i]).add(itemSurfs[i]);
itemSurfs[i].on('click',function(mouseEventArgs){
alert('Buy some really good '+mouseEventArgs.origin.menuData.text);
});
};
var menuState=true;
// make menu go away
function menuFadeOut() {
if(menuState) {
for (var i=0;i<todaysSpecials.length;i++) {
itemMod1[i].setTransform(Transform.translate(-150, 200+i*40, 0));
itemMod2[i].setTransform(Transform.rotateZ(-Math.PI/5.5));
}
menuState=false;
}
}
// bring menu in
function menuFadeIn() {
if(!menuState) {
for (var i=0;i<todaysSpecials.length;i++) {
itemMod1[i].setTransform(Transform.translate(0,100+i*40, -1),{ duration : 300+i*200, curve: 'easeInOut' });
itemMod2[i].setTransform(Transform.rotateZ(-Math.PI/5.5));
}
menuState=true;
}
}
// app initial conditions...
coverReset();
menuFadeOut();
});
Related
How can one access the target of an event, say a click, form the code?
I have:
var eh = new EventHandler();
and
eh.on('click', function(obj) {
rc.setOptions(
{
inTransition: true,
outTransition: false
});
var surfaceProps = obj.origin.getProperties();
as part of a sample app. The surfaces created in a function before in the code pipe click events to this eh event handler as;
surf.pipe(eh);
However, The clicks does not work as expected. In JS console it gives the following error:
TypeError: undefined is not an object (evaluating 'obj.origin.getProperties')
In the sample app, they are referring to a custom event emitted from within the selection within their Scrollview to an EventHandler. The article you refer to was written early in the releases of Famo.us.
The code snippet below will show how this could be done using the 'click' as the custom event. Probably not best practices, because it is an event for the mouse click event (MouseEvent). I would rename it to something else in a production app.
define('main', function(require, exports, module) {
var Engine = require('famous/core/Engine');
var OptionsManager = require('famous/core/OptionsManager');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var EventHandler = require('famous/core/EventHandler');
var StateModifier = require('famous/modifiers/StateModifier');
var RenderNode = require('famous/core/RenderNode');
var View = require('famous/core/View');
var Transform = require('famous/core/Transform');
var SequentialLayout = require("famous/views/SequentialLayout");
var mainContext = Engine.createContext();
var sequentialLayout = new SequentialLayout();
var surfaces = [];
sequentialLayout.sequenceFrom(surfaces);
var eh = new EventHandler();
eh.on('click', function(obj) {
console.log('obj event', obj.event);
var surfaceProps = obj.origin.getProperties();
console.log('obj properties', JSON.stringify(surfaceProps));
});
function _eventHandler(e) {
console.log('event', e, this);
var surfaceProps = this.getProperties();
console.log('surfaceProps', surfaceProps);
this.setContent(JSON.stringify(surfaceProps));
eh.emit('click', {
event: e,
origin: this
});
};
var numberofItems = 10;
var itemHeight = 45;
var itemWidth = 20;
for (var i = 0; i < numberofItems; i++) {
var surface = new Surface({
properties: {
backgroundColor: "hsl(" + (i * 360 / 120) + ", 100%, 50%)",
}
});
surface._mod = new StateModifier({
size: [itemWidth, itemHeight], // <- Changed the width here!!!
origin: [0.5, 0],
align: [0.5, 0],
proportions: [i + 1, 1]
});
var view = new RenderNode();
view.add(surface._mod).add(surface);
view._surface = surface;
surfaces.push(view);
//surface.pipe(eh);
surface.on('click', _eventHandler);
}
mainContext.add(sequentialLayout);
Engine.on('click', function(e) {
for (var i = 0; i < surfaces.length; i++) {
var random = Math.random() * surfaces.length + itemWidth;
surfaces[i]._surface._mod.setProportions([random, 1], {
duration: 1000
});
}
});
});
require(['main']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://requirejs.org/docs/release/2.1.16/minified/require.js"></script>
<script src="http://code.famo.us/lib/requestAnimationFrame.js"></script>
<script src="http://code.famo.us/lib/classList.js"></script>
<script src="http://code.famo.us/lib/functionPrototypeBind.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.famo.us/famous/0.3.5/famous.css" />
<script src="http://code.famo.us/famous/0.3.5/famous.min.js"></script>
<div class="test-container">
<div id="famous-app"></div>
</div>
If I'm understanding your question correctly, this feature just landed in the latest release:Add the famous source object to forwarded events
Now you can just do:
eh.on('click', function(event) {
var famousSurface = event.target;
var domElement = famousSurface._currentTarget;
});
I'm new to Famo.us and I am trying to expand on the Timbre sample app by adding a scrollview to the PageView where the image would be (in the _createBody function). In other words, I'm trying to add a feed similar to Facebook or Tango, etc. I found two pieces of code online that's been working with (links below). I get no errors on the console log, yet the scrollview won't display, so I'm not sure what I am missing. Your guidance is much appreciated (would also love to know if there is a better way). Finally, this is my first post ever on StackOverflow, so please let me know if I can expose my issue in a better fashion.
Links I have been using for guidance:
StackOverflowFamo.us swipe on scrollview
JSFiddle
/*** AppView.js ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Easing = require('famous/transitions/Easing');
var Transitionable = require('famous/transitions/Transitionable');
var GenericSync = require('famous/inputs/GenericSync');
var MouseSync = require('famous/inputs/MouseSync');
var TouchSync = require('famous/inputs/TouchSync');
GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});
var PageView = require('views/PageView');
var MenuView = require('views/MenuView');
var StripData = require('data/StripData');
function AppView() {
View.apply(this, arguments);
this.menuToggle = false;
this.pageViewPos = new Transitionable(0);
_createPageView.call(this);
_createMenuView.call(this);
_setListeners.call(this);
_handleSwipe.call(this);
}
AppView.prototype = Object.create(View.prototype);
AppView.prototype.constructor = AppView;
AppView.DEFAULT_OPTIONS = {
openPosition: 276,
transition: {
duration: 300,
curve: 'easeOut'
},
posThreshold: 138,
velThreshold: 0.75
};
function _createPageView() {
this.pageView = new PageView();
this.pageModifier = new Modifier({
transform: function() {
return Transform.translate(this.pageViewPos.get(), 0, 0);
}.bind(this)
});
this._add(this.pageModifier).add(this.pageView);
}
function _createMenuView() {
this.menuView = new MenuView({ stripData: StripData });
var menuModifier = new StateModifier({
transform: Transform.behind
});
this.add(menuModifier).add(this.menuView);
}
function _setListeners() {
this.pageView.on('menuToggle', this.toggleMenu.bind(this));
}
function _handleSwipe() {
var sync = new GenericSync(
['mouse', 'touch'],
{direction : GenericSync.DIRECTION_X}
);
this.pageView.pipe(sync);
sync.on('update', function(data) {
var currentPosition = this.pageViewPos.get();
if(currentPosition === 0 && data.velocity > 0) {
this.menuView.animateStrips();
}
this.pageViewPos.set(Math.max(0, currentPosition + data.delta));
}.bind(this));
sync.on('end', (function(data) {
var velocity = data.velocity;
var position = this.pageViewPos.get();
if(this.pageViewPos.get() > this.options.posThreshold) {
if(velocity < -this.options.velThreshold) {
this.slideLeft();
} else {
this.slideRight();
}
} else {
if(velocity > this.options.velThreshold) {
this.slideRight();
} else {
this.slideLeft();
}
}
}).bind(this));
}
AppView.prototype.toggleMenu = function() {
if(this.menuToggle) {
this.slideLeft();
} else {
this.slideRight();
this.menuView.animateStrips();
}
};
AppView.prototype.slideLeft = function() {
this.pageViewPos.set(0, this.options.transition, function() {
this.menuToggle = false;
}.bind(this));
};
AppView.prototype.slideRight = function() {
this.pageViewPos.set(this.options.openPosition, this.options.transition, function() {
this.menuToggle = true;
}.bind(this));
};
module.exports = AppView;
});
/*** PageView.js ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var HeaderFooter = require('famous/views/HeaderFooterLayout');
var ImageSurface = require('famous/surfaces/ImageSurface');
var Scrollview = require('famous/views/Scrollview');
function PageView() {
View.apply(this, arguments);
_createBacking.call(this);
_createLayout.call(this);
_createHeader.call(this);
_createBody.call(this);
_setListeners.call(this);
}
PageView.prototype = Object.create(View.prototype);
PageView.prototype.constructor = PageView;
PageView.DEFAULT_OPTIONS = {
headerSize: 44
};
function _createBacking() {
var backing = new Surface({
properties: {
backgroundColor: 'black',
boxShadow: '0 0 20px rgba(0,0,0,0.5)'
}
});
this.add(backing);
}
function _createLayout() {
this.layout = new HeaderFooter({
headerSize: this.options.headerSize
});
var layoutModifier = new StateModifier({
transform: Transform.translate(0, 0, 0.1)
});
this.add(layoutModifier).add(this.layout);
}
function _createHeader() {
var backgroundSurface = new Surface({
properties: {
backgroundColor: 'black'
}
});
this.hamburgerSurface = new ImageSurface({
size: [44, 44],
content : 'img/hamburger.png'
});
var searchSurface = new ImageSurface({
size: [232, 44],
content : 'img/search.png'
});
var iconSurface = new ImageSurface({
size: [44, 44],
content : 'img/icon.png'
});
var backgroundModifier = new StateModifier({
transform : Transform.behind
});
var hamburgerModifier = new StateModifier({
origin: [0, 0.5],
align : [0, 0.5]
});
var searchModifier = new StateModifier({
origin: [0.5, 0.5],
align : [0.5, 0.5]
});
var iconModifier = new StateModifier({
origin: [1, 0.5],
align : [1, 0.5]
});
this.layout.header.add(backgroundModifier).add(backgroundSurface);
this.layout.header.add(hamburgerModifier).add(this.hamburgerSurface);
this.layout.header.add(searchModifier).add(searchSurface);
this.layout.header.add(iconModifier).add(iconSurface);
}
function _createBody() {
var surfaces = [];
this.scrollview = new Scrollview();
var temp;
for (var i = 0; i < 30; i++) {
temp = new Surface({
size: [undefined, 80],
content: 'Surface: ' + (i + 1),
properties: {
textAlign: 'left',
lineHeight: '80px',
borderTop: '1px solid #000',
borderBottom: '1px solid #fff',
backgroundColor: '#ffff00',
fontFamily: 'Arial',
backfaceVisibility: 'visible',
paddingLeft: '10px'
}
});
temp.pipe(this.scrollview);
surfaces.push(temp);
}
this.scrollview.sequenceFrom(surfaces);
this.bodyContent = new Surface({
size: [undefined, undefined],
properties: {
backgroundColor: '#f4f4f4'
}
});
this.layout.content.add(this.bodyContent);
}
function _setListeners() {
this.hamburgerSurface.on('click', function() {
this._eventOutput.emit('menuToggle');
}.bind(this));
//this.bodyContent.pipe(this._eventOutput);
this.scrollview.pipe(this._eventOutput);
}
module.exports = PageView;
});
You need to add this.scrollview to your layout.content element on the page. Put this in place of this.bodyContent. layout.content is the node for the content of the page.
//this.layout.content.add(this.bodyContent);
this.layout.content.add(this.scrollview);
If I have a surface that hase conent that includes an input. The input doesn't seem to gain focus on click.
Here is how I include my surface.
var ConfigureView = function() {
this.initialize.apply(this, arguments);
};
_.extend(ConfigureView.prototype, {
template: templates['config'],
initialize: function( options ) {
var position = new Transitionable([0, 0]);]
var sync = new GenericSync({
"mouse" : {},
"touch" : {}
});
this.surface = new Surface({
size : [200, 200],
properties : {background : 'red'},
content: this.template()
});
// now surface's events are piped to `MouseSync`, `TouchSync` and `ScrollSync`
this.surface.pipe(sync);
sync.on('update', function(data){
var currentPosition = position.get();
position.set([
currentPosition[0] + data.delta[0],
currentPosition[1] + data.delta[1]
]);
});
this.positionModifier = new Modifier({
transform : function(){
var currentPosition = position.get();
return Transform.translate(currentPosition[0], currentPosition[1], 0);
}
});
var centerModifier = new Modifier({origin : [0.5, 0.5]});
centerModifier.setTransform(Transform.translate(0,0));
},
addTo: function(context) {
context = Engine.createContext()
context.add(this.positionModifier).add(this.surface);
}
});
module.exports = ConfigureView;
What is necessary to make forms act normally with famo.us?
Or do i just need to have an inner surface that has a different listener?
This is templates['config']:
templates["config"] = Handlebars.template({"compiler":[5,">= 2.0.0"],"main":function(depth0,helpers,partials,data) {
return "<input type=\"text\" id=\"fontSize\" >";
},"useData":true});
What displays is an input I just can't seem to focus on it.
UPDATE
The reason I think I couldn't focus was because I wasn't using an inputSurface and the surface event was being pipe away. Using a scrollView I was able to make it work.
var ConfigureView = function() {
this.initialize.apply(this, arguments);
};
_.extend(ConfigureView.prototype, {
template: templates['config'],
initialize: function( options ) {
this.app = options.app;
var position = new Transitionable([0, 0, 1000]);
this.scrollView = new ScrollView();
var surfaces = [];
this.scrollView.sequenceFrom(surfaces);
// create a sync from the registered SYNC_IDs
// here we define default options for `mouse` and `touch` while
// scrolling sensitivity is scaled down
var sync = new GenericSync({
"mouse" : {},
"touch" : {}
});
this.surface = new Surface({
size : [200, 200],
properties : {background : 'red'},
content: this.template()
});
surfaces.push(this.surface);
this.offsetMod = new Modifier({ origin: [0.2,0,2]});
this.inner = new Surface({
size : [100, 100],
properties : {background : 'gray'},
content: this.template()
});
surfaces.push(this.inner);
// now surface's events are piped to `MouseSync`, `TouchSync` and `ScrollSync`
this.surface.pipe(sync);
this.inputsFontSize = new InputSurface({
classes: ['login-form'],
content: '',
size: [300, 40],
placeholder:'email',
properties: {
autofocus:'autofocus',
maxLength:'5',
textAlign: 'left'
}
});
sync.on('update', function(data){
var currentPosition = position.get();
position.set([
currentPosition[0] + data.delta[0],
currentPosition[1] + data.delta[1]
]);
});
this.positionModifier = new Modifier({
transform : function(){
var currentPosition = position.get();
return Transform.translate(currentPosition[0], currentPosition[1], 0);
}
});
var centerModifier = new Modifier({origin : [0.5, 0.5]});
centerModifier.setTransform(Transform.translate(0,0));//, y, z))
},
addTo: function(context) {
context = Engine.createContext();
context.add(this.positionModifier).add(this.scrollView);
}
});
module.exports = ConfigureView;
I'm trying to implement a slide to delete. As part of that I have a layer with opacity set to 0 the idea being I'm trying to set several if clauses to gradual change the opacity of the surface so that the word Delete gentle appears as you slide it to the left. At this point I just have it switching at 10pixels for testing. The functions fire but the opacity doesn't change. I think it has something to do with not being piped/event handling being done properly on my part. Any Ideas?
var SnapTransition = require("famous/transitions/SnapTransition");
Transitionable.registerMethod('snap', SnapTransition);
var CSS = require("css/recentActivityCSS");
var Ctrl = require("controllers/recentActivityCtrl");
var homeContentWrap = new Scrollview();
var recentActivities = [];
var ContainerSize = [undefined, 100];
homeContentWrap.sequenceFrom(recentActivities);
for (var i = 0; i < Ctrl.recentActivityList.length; i++) {
var recentActivitiesContainer = new ContainerSurface({
size: ContainerSize,
properties: CSS.recentActivitiesContainer,
});
var redLayer = new Surface({
size: ContainerSize,
content: 'DELETE',
properties: CSS.redLayer,
});
var draggable = new Draggable({
xRange: [-120, 5],
yRange: [0, 0],
});
var textContainer = new ContainerSurface({
size: ContainerSize,
properties: CSS.textContainer,
});
var mod = new Modifier({});
node = new RenderNode(draggable);
node.add(mod).add(textContainer);
textContainer.pipe(draggable);
textContainer.pipe(homeContentWrap);
var opacityMod = new StateModifier({
opacity: 0
});
recentActivitiesContainer.add(node);
recentActivitiesContainer.add(opacityMod).add(redLayer);
recentActivities.push(recentActivitiesContainer);
var trans = {
method: 'snap',
period: 100,
dampingRatio: 0.3,
velocity: 5
};
draggable.on('start', function() {});
draggable.on('update', function() {
var position = this.getPosition();
if (position[0] > (-10)) {
opacityMod.halt();
opacityMod.setOpacity(0, { curve: 'easeOut', duration: 10 });
} else {
opacityMod.halt();
opacityMod.setOpacity(1, { curve: 'easeOut', duration: 10 });
}
});
draggable.on('end', function(){
var position = this.getPosition();
if (position[0] < (-100)) {
alert('delete');
}
this.setPosition([0,0,0], trans);
});
There are a couple of things I did to the draggable 'update' function to achieve what you have described.
1) You need to bind objects to your update function or else you have no real reference to them. When you use opacityMod in your 'update' function, you only alter the last cells opacityMod. Since binding will change the meaning of 'this', I also bind draggable.
2) You say you want a gradual fade. This approach is not going to give you anything gradual. You need to take the position of the draggable and calculate an opacity based on that value. To start, I declare two new variables for fadeStart and fadeEnd, that represent the positions of the draggable X position 0 and 1 opacity respectively.
Also you probably do not need the transition in your setOpacity, but I kept it in anyway.
Here is the updated 'update' function.. Good Luck!
fadeStart = -10;
fadeEnd = -100;
draggable.on('update', function() {
var draggable = this[0];
var opacityMod = this[1];
var position = draggable.getPosition();
if ( position[0] > fadeStart ) {
opacityMod.halt();
opacityMod.setOpacity(0, { curve: 'easeOut', duration: 10 });
} else if ( position[0] > fadeEnd ) {
opacity = (position[0] - fadeStart) / ( fadeEnd - fadeStart );
opacityMod.halt();
opacityMod.setOpacity(opacity, { curve: 'easeOut', duration: 10 });
} else {
opacityMod.halt();
opacityMod.setOpacity(1, { curve: 'easeOut', duration: 10 });
}
}.bind([draggable,opacityMod]));
John has clearly answered this question above, but I wanted to show an alternate approach to the problem. I've seen questions here and in the #famous irc where people are having eventing problems. I've also seen a number of people struggling with binding or the lack of it. And finally, if you work out the whole slide thing here, shouldn't you be able to put that behind you and simply drop it in elsewhere? With that in mind I wrote a program that simply puts several images into a scrollview. Then I wrote a function called createSlidePanel that encapsulated the slide functionality and then to enable the fade-in of the word "delete" I created a second helper function createModifyingView. This approach appears to hit all three points above. I broke the eventing problems down into smaller more manageable units. It completely eliminated the need for this and binding. And finally, the two helper functions can be reused.
Here is my version of "main.js" which contains fundamentally "application" behavior:
/* globals define */
define(function(require, exports, module) {
'use strict';
// import dependencies
var Engine = require('famous/core/Engine');
var ImageSurface = require('famous/surfaces/ImageSurface');
var Surface = require('famous/core/Surface');
var Scrollview = require('famous/views/Scrollview');
var SnapTransition = require('famous/transitions/SnapTransition');
var Transitionable = require('famous/transitions/Transitionable');
var createSlidePanel = require('SlidePanel');
var createModifyingView = require('ModifyingView');
Transitionable.registerMethod('snap', SnapTransition);
var trans = {
method: 'snap',
period: 100,
dampingRatio: 0.3,
velocity: 5
};
var dataSource = [
'http://www.outerspaceuniverse.org/wp-content/uploads/2009/07/outer-space1.jpg',
'http://wallpoper.com/images/00/39/95/84/outer-space_00399584.jpg',
'http://static1.businessinsider.com/image/508c649e69beddb270000005/the-only-reason-private-space-flight-isnt-laughed-at-is-nasas-11-billion-infusion.jpg'
];
var images = [];
var slideOptions = {
drag: {
xRange: [-120, 5],
projection: 'x',
},
view: {
size:[300,300]
}
};
var mainContext = Engine.createContext();
var scrollView = new Scrollview();
mainContext.add(scrollView);
dataSource.forEach(function(url,i,urls) {
var img = new ImageSurface({
content: url,
size: [300,300]
});
var dlt = new Surface({
size:[300,300],
content: 'DELETE',
properties: {
color: 'red',
zIndex: 4,
lineHeight: '200px',
fontSize:'60px'
}
});
var modView = createModifyingView();
modView.modifier.setOpacity(0);
modView.add(dlt);
var elem = createSlidePanel(slideOptions);
elem.addSlide(img)
elem.addStill(modView);
elem._eventOutput.pipe(scrollView);
elem.on('slideupdate',slideUpdateHandler);
elem.on('slideend',slideEndHandler);
images.push(elem);
});
function slideUpdateHandler(eventInfo) {
var ratio = (eventInfo.data.position[0]-slideOptions.drag.xRange[1])/(slideOptions.drag.xRange[0]-slideOptions.drag.xRange[1]);
if(ratio>.2) {
eventInfo.source.stillElements[0].modifier.setOpacity(ratio);
} else {
eventInfo.source.stillElements[0].modifier.setOpacity(0);
}
}
function slideEndHandler(eventInfo) {
if (eventInfo.data.position[0] < (-100)) {
alert('delete');
}
eventInfo.source.modifier.setPosition([0,0,0], trans);
eventInfo.source.stillElements[0].modifier.setOpacity(0);
}
scrollView.sequenceFrom(images);
});
The slide functionality is here in "SlidePanel.js":
/* globals define */
define(function(require, exports, module) {
'use strict';
// import dependencies
var Modifier = require('famous/core/Modifier');
var View = require('famous/core/View');
var Draggable = require('famous/modifiers/Draggable');
function createSlidePanel(options) {
options = options || {};
var slidePanel = new View(options.view);
slidePanel.slideElements = [];
slidePanel.stillElements = [];
slidePanel.modifier = new Draggable(options.drag);
var node = slidePanel._add(slidePanel.modifier);
slidePanel.addSlide = function addSlide(renderable) {
node.add(renderable);
renderable.pipe(slidePanel._eventOutput);
renderable.pipe(slidePanel.modifier);
slidePanel.slideElements.push(renderable);
}
slidePanel.addStill = function addStill(renderable) {
slidePanel.add(renderable);
renderable.pipe(slidePanel._eventOutput);
renderable.pipe(slidePanel.modifier);
slidePanel.stillElements.push(renderable);
}
slidePanel.modifier.on('start',function(data) {
slidePanel._eventOutput.emit('slidestart',{source:slidePanel,data:data});
});
slidePanel.modifier.on('update',function(data) {
slidePanel._eventOutput.emit('slideupdate',{source:slidePanel,data:data});
});
slidePanel.modifier.on('end',function(data) {
slidePanel._eventOutput.emit('slideend',{source:slidePanel,data:data});
});
slidePanel.modifier.activate();
return slidePanel;
}
module.exports = createSlidePanel;
});
And here is the "ModifyingView.js" code:
/* globals define */
define(function(require, exports, module) {
'use strict';
// import dependencies
var Modifier = require('famous/core/Modifier');
var View = require('famous/core/View');
function createModifyingView(options) {
options = options || {};
var view = new View(options);
view.modifier = new Modifier();
var node = view._add(view.modifier);
view.add = function add(renderable) {
node.add(renderable);
view._eventOutput.subscribe(renderable);
};
view.setPosition = function setPosition(/* passthrough */) {
view.modifier.setPosition(arguments);
};
view.setOpacity = function setOpacity(/* passthrough */) {
view.modifier.setOpacity(arguments)
}
//view.modifier.setPosition([0,0,0]);
return view;
}
module.exports = createModifyingView;
});
Several Notes:
Obviously, one of the main changes here is the functional pattern which makes all references explicit and leaves no question of binding.
Yes this is more code than the original, partly because it is complete with all of the require statements and the list of images, but also because it just is. The trade-off here is that you may get more bang for the buck if you reuse the helpers.
The ModifyingView pattern is one I use quite a bit. This comes up so often whether I'm building a login form with eight surfaces interacting in ways the main program need know nothing about, or a simple surface fading in and out, that I have a code snippet which defines a view, a modifier, a statemodifier (one of which I usually delete,) a surface and much of the common code to tie them together.
I'm specifically not recommending the "options" management used in this code, but it suffices for the example.
I'm trying to implement the typical swipe left event to trigger some custom action using a scrollview in famo.us. The thing is that I missing something and I can't get it done. I manage to implement a Draggable modifier in each scrollview item, so the items can be dragged (X axis), but now I can't be able to capture the event of the draggable modifier in order to trigger the actions.
Here is my ListView class:
define(function(require, exports, module) {
// Imports
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Utility = require('famous/utilities/Utility');
var ScrollView = require('famous/views/ScrollView');
var ViewSequence = require('famous/core/ViewSequence');
var Draggable = require('famous/modifiers/Draggable');
var RenderNode = require('famous/core/RenderNode');
var EventHandler = require('famous/core/EventHandler');
function ListView() {
View.apply(this, arguments);
this.items = [];
this.scrollView = new ScrollView({
direction: Utility.Direction.Y,
margin: 100000
});
this.viewSequence = new ViewSequence(this.items);
this.scrollView.sequenceFrom(this.viewSequence);
this._add(this.scrollView);
};
ListView.prototype = Object.create(View.prototype);
ListView.prototype.constructor = ListView;
ListView.prototype.setContent = function(data) {
for (var i = 0; i < data.length; i++) {
var item = new Surface({
size: [undefined, 60],
content: 'Item ' + data[i],
classes: ['listview-item']
});
var draggable = new Draggable({
xRange: [-100, 100],
yRange: [0, 0]
});
var node = new RenderNode(draggable);
node.add(item);
draggable.on('click', function() {
console.log('emit swipe')
this._eventOutput.emit('swipe');
}.bind(this)); // This Doesn't work
item.on('click', function() {
console.log('emit swipe')
this._eventOutput.emit('swipe');
}.bind(this)); // Neither this
item.pipe(draggable);
item.pipe(this.scrollView);
this.items.push(node);
}
};
module.exports = ListView;
});
Now App Class where I include my ListView:
define(function(require, exports, module) {
...
// Custom Views
var ListView = require('views/ListView');
function App() {
View.apply(this, arguments);
this.layout = new HeaderFooterLayout({
headerSize: 70,
});
...
this.list = new ListView();
this.list.pipe(this._eventInput);
this._eventInput.on('swipe', this.swipeListItem.bind(this)) // Trying to captute swipe event
this.list.setContent([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]);
this.layout.content.add(this.list);
....
this._add(this.layout);
};
App.prototype = Object.create(View.prototype);
App.prototype.constructor = App;
App.DEFAULT_OPTIONS = {};
App.prototype.swipeListItem = function() {
console.log('Item Swiped!');
};
module.exports = App;
});
I don't know what I missing or if there is a better way to implement a swipe gesture in famo.us, if someone knows something about it would be helpful.
Thanks in advance. =)
It looks like you want to use the 'start' event for the draggable modifier..
draggable.on('start', function() {
console.log('emit drag start')
this._eventOutput.emit('swipe');
}.bind(this));
Draggable also emits 'update', and 'end' and each of these handlers take a parameter that returns the position of the draggable
draggable.on('update', function(e) {
// Do something on update
var pos = e.position;
});
draggable.on('end', function(e) {
// Do something on end
var pos = e.position;
});
Hope this helps!