EzDevInfo.com

page.js

Micro client-side router inspired by the Express router Page.js by visionmedia

How to get page.js to work in a single page AND multipage on the same site?

am using page.js for routing in a Grails application using '/' to point /HomeController/index to serve up a single page web application. I just installed Grails Spring Security Core plugin, and I am using the Grails scaffolding to create the User Admin/Permissions views with the goal of serving them in the traditional multi-page way to avoid having to do a lot of UI work on admin pages. The bulk of the application will be served using single page architecture, with just the admin pages being served multi-page.

In their documentation, page.js says, "By default when a route is not matched, page.js will invoke page.stop() to unbind itself, and proceed with redirecting to the location requested. This means you may use page.js with a multi-page application without explicitly binding to certain links." But, I cannot get it to work...

I am using page.js like so:

page('/', SCM.Dashboard.home);
page('/hx', SCM.HX.summary);
page('/hx/vendor', SCM.HX.vendors);
page('/hx/customer', SCM.HX.customers);
page('/customer/list', SCM.Customer.list);
page('/maintenance/activity', SCM.Maintenance.activity);
page();

When I click a link to '/user', based on their documentation, I expect it to forward directly to 'http://domain.com/user'. It adds the correct path to browser location bar (http://domain.com/user), but the browser never forwards to the page. In order to see the page, I have to click the link, and after the location bar has changed, if I refresh the browser window, the correct page appears - obviously unacceptable. Yet, I cannot find in their documentation how to implement this correctly. I have experimented with various settings for hours with no luck. If I comment out the page.js code above, the multi-page admin pages work fine, and I am able to navigate from page to page no problem. Has anyone solved this problem?


Source: (StackOverflow)

client-side routing with page.js between two different spa pages

We are building an application using multiple single-page apps to keep things small, but run into a problem of building links between pages.

Let's say we have to pages equipment.html and maintenance.html

Both are independent SPA apps each with their own client side roting tables Right now we have client side routing with page.js using #!

On the equipment page we place a link <a rel='nofollow' href="/maintenance.html#!/show/350">Show Maintenance</a>

Hovering over the link shows http://localhost/maintenance.html#!/show/350 but when we click on the links it goes to http://localhost/equipment.html#!/maintenance.html#!/show/350 which does not take us anywhere. Now, clicking second time on the link takes us to the right page. Any way to solve this?

Thanks


Source: (StackOverflow)

Advertisements

Bookmarking in SPA with page.js using deep links and pretty url

I am getting into SPA programming and have a working app with page.js. I searched stackoverflow and page.js but cannot figure out how to process the URL requests like /record/Name1 when a page is reloaded (or loaded after being shared or bookmarked).

The only way I see is to use history API and refer to an file like record.php?id=name. But I believe there are better / more beautiful ways as done on stockoverflow. Could someone point me to a tutorial or sample for the next step. I would like to avoid frameworks like jquery (but will use Polymer).

Here my test code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Page.js test</title>
    </head>

    <body style="font-family: sans-serif;">
        <h2>Menu:</h2>
        <div>
            <a rel='nofollow' href="/">Home</a><br>
            <a rel='nofollow' href="/records">Records</a><br>
            <a rel='nofollow' href="/record/Name1">Record/Name1</a><br>
            <a rel='nofollow' href="/record/Name2">Record/Name2</a><br>
            <a rel='nofollow' href="/index_1.html" rel="external">external</a><br>
        </div>
        <hr>
        <h2>Content:</h2>
        <p id="main"></p>
    </body>

    <script src="bower_components/page/page.js"></script>
    <script>
        page('/', function () {
            document.getElementById("main").innerHTML = "Home";
        });
        page('/records', function () {
            document.getElementById("main").innerHTML = "Records";
        });
        page('/record/:name', function (ctx) {
            document.getElementById("main").innerHTML = ctx.params.name;
            //history.pushState(null, null, ctx.params.name);
        });
        page({
            hashbang: false // do not add #! before urls
        });
    </script>
</html>

Thanks for the help.


Source: (StackOverflow)

node with page js structure

I am new in node js and I am working with page js. I want to improve my way of coding, so I have to ask if I am doing it in the right way.

In my lib structure I have:

schedule
├── schedule.js
├── styles.styl
├── template.jade
schedules
├── index.js
├── model.js

In schedules/index.js:

var app = require('express')()
var logger = require('../logger')
var _ = require('lodash')
var Schedule = require('./model')

app.get('/schedules', function(request, response){
    Schedule.find({}).exec()
        .then(function(schedules){

            var schedulesFixed = schedules.map(function(schedule){
                return schedule.toJSON()
            })

        response
            .status(200)
            .set('Content-Type', 'application/json')
            .json({
                schedules: schedulesFixed
            })
    }, function(err){
        logger.info('err', err)
    })
})

module.exports = app

And in schedule/schedule.js

var $ = require('jquery')
var page = require('page')
var scheduleTemplate = require('./template.jade')

function Schedule(selector){
    $(selector).css('background-image', 'none');
    $(selector).css('background-color', '#d5d5d5');
    $(selector).html(scheduleTemplate)  

    var tableContent = '';

    $.getJSON( '/schedules', function( data ) {

        $.each(data.schedules, function(){

            tableContent += '<tr>'
            tableContent += '<td>' + this.date + '</td>'
            tableContent += '<td>' + this.hourStart + '</td>';
            tableContent += '<td>' + this.hourEnd + '</td>';
            tableContent += '<td>' + this.phycologist + '</td>';
            tableContent += '<td>' + this.patient + '</td>';            
            tableContent += '</tr>'

        });

        $('#userList table tbody').html(tableContent);
    });

}

module.exports = Schedule

What can I improve, the folder structure, the way of calling the '/schedules' url?


Source: (StackOverflow)

not able to do routing properly in page.js

I am using page.js for routing in a Single Page Application. For testing purpose, I am using npm http-server.

I am not able to do routing. I am not sure what I am missing. following is my code:

index.html:

<html>
<head>
  <title>test page!</title>
  <script src="/js/libs/page.js"></script>
</head>
<body>
  this is body of test
  <a rel='nofollow' href="/test">Simple test</a>

  <script type="text/javascript" src="/js/routes.js"></script>
</body>
</html>

routes.js

function initRoutes () {
  var testRoutes = {
    test : function (context, next) {
      alert("testing");

      if(next){
        next();
      }
    },
    test2 : function (context, next) {
      alert("I am jon snow, I know nothing.");
    }
  };
  page.base('/');

  page('/', testRoutes.test);
  page('/test', testRoutes.test2);
  page('/two-args', testRoutes.test, testRoutes.test2);
  page();
}
initRoutes();

from my http-server, I am accessing http://0.0.0.0:8081. I am getting an test as alert, but I am not getting the alert for route http://0.0.0.0:8081/test.

I am not sure what I am missing. Please let me know if you need anything else.


Source: (StackOverflow)

capture a regex group in url with pagejs

I want more than one optinal parameters in pagejs so I cannot go like this /controller/action/:p1?/:p2? because If p1 is not provided, value will be set to p1 instead of p2. So I went for this url form: /controller/action/p1/:p1/p2/:p2 but this obligates the url to receive both param, so optional is now allowed, So I'd like to make both param prefix and param receiver optional within a regex group, going in this url way: /controller/action(/p1/:p1)?(/p2/:p2)? however it doesn't work, it sets a function to p1...

any help on achieve this on pagejs ?

https://github.com/visionmedia/page.js


Source: (StackOverflow)

Polymer Routing with page.js do not add hashbang to URLs when links are opened in new tab

I am using polymer starter kit which uses page.js for routing. The hashbang page option is set to true in routing.html

// add #! before urls
page({
  hashbang: true
});

when links such as <a rel='nofollow' href="/products/productname"></a> are clicked, the #! is added and the resulting url looks like this: http://localhost:3000/#!/products/productname but when the links are opened in a new browser tab, they look like this http://localhost:3000/products/productname. How can I have the #! added when links are opened in new tab?


Source: (StackOverflow)

How to instantiate route in a Polymer app located on an internal page of a site using page.js

I'm attempting to run a Polymer app on an internal page of a site and having an issue setting the initial route. The app is located at 127.0.0.1:8080/hardware on local dev.

My custom Element looks like this:

<link rel="import" rel='nofollow' href="../../polymer/polymer.html" />
<link rel="import" rel='nofollow' href="../../iron-flex-layout/iron-flex-layout.html" />
<link rel="import" rel='nofollow' href="../../iron-pages/iron-pages.html" />
<link rel="import" rel='nofollow' href="../../iron-selector/iron-selector.html" />

<dom-module id="category-select">
  <style>
    :host {} iron-selector {
      @apply(--layout-horizontal);

@apply(--layout-wrap);

@apply(--layout-justified);

    }
    .fig-wrap {
      @apply(--layout-flex);

margin: 0 .8rem;
      min-width: 150px;
    }
    .fig-wrap figure img {
      margin: 0 auto;
      display: block;
    }
    figcaption {
      padding-top: 5px;
    }
    .fig-wrap figure figcaption h3 {
      font-size: 1rem;
      text-align: center;
    }
  </style>
  <template>

    <!--Allows selection by dom elements produced in template repeater-->

    <h1>Hey We are looking at the  <span>{{category}}</span>category</h1>
    <a data-route="home" rel='nofollow' href="/hardware">home</a>
    <iron-pages attr-for-selected="data-route" selected="{{route}}">

      <section data-route="home">
        <h1>Home route</h1>
        <a data-route="catz" rel='nofollow' href="/catz">CATZ</a>
        <iron-selector attr-for-selected="name" selected="{{category}}">
          <!-- Acts as a for each loop to repeat-->
          <template is="dom-repeat" items="{{categories}}">
            <div name$="{{item.name}}" class="fig-wrap">
              <!--<a rel='nofollow' href="{{item.link}}">-->
              <figure>
                <img src="{{item.img}}" alt="" />
                <figcaption>
                  <h3>{{item.name}}</h3>
                </figcaption>
              </figure>
              <!--</a>-->
            </div>
          </template>
        </iron-selector>
      </section>

      <section data-route="catz">
        <h1>Category route</h1>
      </section>
    </iron-pages>
  </template>
</dom-module>
<script>
  Polymer({
    is: 'category-select',
    ready: function() {
      this.categories = [{
          name: 'Anchors',
          img: 'https://example.com/img/hardware/anchor.jpg',
          link: 'https://www.example.org/',
          products: [{
            name: 'Anchor',
            image: 'path/to/image.jpg',
            steel: '316 Stainless Steel',
            details: ['precision cut', 'polished from grade 316 stainless steel', 'suitable for both sailboats and powerboats', 'these anchors range in size from 25 lbs to 150 lbs'],
            options: [{
              size: '25 pounds',
              price: '3041.75',
              code: '32442'
            }, {
              size: '35 pounds',
              price: '4203.25',
              code: '4234'
            }, {
              size: '45 pounds',
              price: '5146.25',
              code: '34231'
            }, {
              size: '60 pounds',
              price: '6842.50',
              code: '1224'
            }, {
              size: '80 pounds',
              price: '8912.50',
              code: '1234'
            }, {
              size: '100 pounds',
              price: '11183.75',
              code: '1234'
            }, {
              size: '150 pounds',
              price: '14547.50',
              code: '1234'
            }]
          }, {
            name: 'Cast Iron Grapnel Folding Anchor',
            image: 'string',
            steel: 'Cast Iron Galvanized',
            details: ['products details', 'put them in a list', 'a pretty ul'],
            options: [{
              size: 'string',
              price: 'string',
              code: 'string'
            }]

          }, {
            name: '360° Anchor Swivel',
            image: 'string',
            steel: '17-4 PH Stainless Steel',
            details: ['products details', 'put them in a list', 'a pretty ul'],
            options: [{
              size: 'string',
              price: 'string',
              code: 'string'
            }]

          }, {
            name: 'Universal Anchor Swivel',
            image: 'string',
            steel: '17-4 PH Stainless Steel',
            details: ['products details', 'put them in a list', 'a pretty ul'],
            options: [{
              size: 'string',
              price: 'string',
              code: 'string'
            }]

          }, {
            name: 'Bow Chain Stopper',
            image: 'string',
            steel: '316 Stainless Steel',
            details: ['products details', 'put them in a list', 'a pretty ul'],
            options: [{
              size: 'string',
              price: 'string',
              code: 'string'
            }]

          }, {
            name: 'Anchor Chain & Spliced Rope Anchor Line',
            image: 'string',
            steel: '316L Stainless Steel & 3 Strand Twist',
            details: ['products details', 'put them in a list', 'a pretty ul'],
            options: [{
              size: 'string',
              price: 'string',
              code: 'string'
            }]
          }]
        }, {
          name: 'Chain',
          img: 'https://example.com/img/hardware/chain.jpg',
          link: 'https://www.example.com/'
        }

      ];
    },
    properties: {
      category: {
        computed: '_computeCategory(categories, name)'
      }
    },
    _computeCategory: function(categories, name) {
      return categories[name];
    }
  });
</script>

The custom element is wrapped in a <template is="dom-bind" id=app> on the page.

My routing.html is called from elements.html which looks like this:

<!--Elements from polymer-->
<link rel="import" rel='nofollow' href="../iron-selector/iron-selector.html"/>
<link rel="import" rel='nofollow' href="../iron-image/iron-image.html"/>
<link rel="import" rel='nofollow' href="../paper-button/paper-button.html"/>
<link rel="import" rel='nofollow' href="../paper-material/paper-material.html"/>
<link rel="import" rel='nofollow' href="../iron-flex-layout/iron-flex-layout.html"/>
<!--Custom Elements-->
    <!-- app-theme goes here-->
<link rel="import" rel='nofollow' href="../elements/category-select/category-select.html"/>

<!--Configure routes-->
<link rel="import" rel='nofollow' href="routing.html"/>

And routing.html looks like this:

<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<script src="../page/page.js"></script>
<script>
    window.addEventListener('WebComponentsReady', function() {
        var app = document.querySelector('#app');

        // We use Page.js for routing. This is a Micro
        // client-side router inspired by the Express router
        // More info: https://visionmedia.github.io/page.js/
        page('/hardware', function () {
            app.route = 'home';
        });
        page('/catz', function () {
            app.route = 'catz';
        });
//
//        page('/users', function () {
//            app.route = 'users';
//        });
//
//        page('/users/:name', function (data) {
//            app.route = 'user-info';
//            app.params = data.params;
//        });
//        page('/categories', function () {
//            app.route = 'categories';
//        });
//
//        page('/categories/:name', function (data) {
//            app.route = 'category-info';
//            app.params = data.params;
//        });
//
//
//        page('/contact', function () {
//            app.route = 'contact';
//        });
//        page('/anchors', function () {
//            app.route = 'anchors';
//        });

        // add #! before urls
        page({
            hashbang: true
        });

    });
</script>

I call this script at the bottom of the page:

(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  var app = document.querySelector('#app');
  app.route = 'home';


})(document);

So as a note, before adding the <iron-pages> element my iron selector and dom-repeat template functioned.

My issue now is that when <iron-pages attr-for-selected="data-route" selected="{{route}}"> has its selected set to {{route}} the iron-pages will not display any of the sections but displays a url of hardware/#!/hardware.

When I set iron-pages selected attribute manually to selected="home" the home view displays and iron-selector and dom-repeat both function. Yet when I click on the link to the route catz the view remains the same while the url changes.

console.log(app.route) in the dev tools returns home at all points. I've done my best to emulate the Polymer 1.0 Starter Kit's routing methods but cannot get it to work.

So, how do I go about setting the route to home initially, but then allowing it to change on user interaction?


Source: (StackOverflow)

server side rendering using webpack

I am using Reactjs, webpack along with page.js (routing) to build a webapp. Webpack gives me a bundle.js which is loaded on the client side.

I found out the og Meta tags can't be crawled if I am loading them on the client so, I have to implement it on the server side (server side rendering). Is there any way to implement it ?

(I didn't find proper documentation about this on net).


Source: (StackOverflow)

using page.js with sinatra (or rails)

I would like to know if it's possible to use page.js with sinatra. My images's route are intercepted by Sinatra instead of Page.js

get '/' do
  erb :index
end

__END__

@@ layout
 <!DOCTYPE html>
 <html lang="en">
 <head>
   <title>page.js</title>
   <link rel='nofollow' href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
   <script type="text/javascript" src="page.js"></script>
   <style type="text/css">ul li { display: inline; list-style:none }</style>
 </head>
 <body>
   <%= yield %>
</body>
<script type="text/javascript">
page('/images', function(ctx){
      console.log('page(' + ctx.path + ')');
          $('section#example').html('<h2 class="text-center">Listing of Images</h2>');
});
/*... /videos ..*/
page('*', function(ctx){
      console.log('page(' + ctx.path + ')');
          $('section#example').html('<h2 class="text-center">Error : ' + ctx.path + '</h2>');
});

$('document').ready(function(){page()});

</script>
</html>

@@ index
    <ul>
      <li><a rel='nofollow' href="./">index</a></li>
      <li><a rel='nofollow' href="./videos">videos</a></li>
      <li><a rel='nofollow' href="./images">images</a></li>
    </ul>
   <section id="example" class="well"></section>
   <h1>hello world</h1>

Source: (StackOverflow)

cant make new routing in Polymer 1.0 starter-kit (via page.js and iron-page)

i am new to polymer and i just start it with Polymer 1.0 starter-kit

i understand the structure of Polymer app and used the page.js for making a new rout like this.

window.addEventListener('WebComponentsReady', function() {

    // We use Page.js for routing. This is a Micro
    // client-side router inspired by the Express router
    // More info: https://visionmedia.github.io/page.js/
    page('/', function () {
      app.route = 'home';
    });

    page('/users', function () {
      app.route = 'artworks';
    });

//my new routing def. <<<<<<<<
    page('/artworks', function () {
      app.route = 'artworks';
    });

    page('/users/:name', function (data) {
      app.route = 'user-info';
      app.params = data.params;
    });

    page('/contact', function () {
      app.route = 'contact';
    });

    // add #! before urls
    page({
      hashbang: true
    });

  });

as i understood the page.js sets the app.route to some values and the Polymer iron-pages uses the app.route to select the right section to show with selected="{{route}}" the code is like this:

<iron-pages attr-for-selected="data-route" selected="{{route}}">
  <section data-route="home">home section</section>
  <section data-route="users">users section</section>
  <section data-route="artworks">artworks section</section>
  <section data-route="user-info">user-info section</section>
  <section data-route="contact">contact section</section>
</iron-pages>

after all what is the problem!? well when i use localhost:8000/artworks the page.js wont change it to localhost:8000/#!/artworks but it do just the same for every other routed address like localhost:8000/users or localhost:8000/contact as a result the web browser will search for the file at localhost:8000/artworks folder and finds nothing so a 404 err will occur.

i can not understand now. what did i missed here? any idea?


Source: (StackOverflow)

Polymer Page.js paper-header-panel element scroll top when menu item selected

I have a problem with paper-menu and paper-header-panel. When I click on my paper-menu items and webcomponents has correctly loaded the relative page, this one appears in the previous scrolled position. How I can set to scroll on top when the click is performed??


Source: (StackOverflow)

Polymer app routing partials with Page.js

I'm using the Polymer Starter Kit and would like have each route's content in a separate file (/pages/games.html, /pages/movies.html, etc) but I can't find any examples of this.

Could someone point me in the right direction? Or is it not possible or recommended to implement routing like this?


Source: (StackOverflow)