Getting Start with Ember.js Router

2019-05-07 10:50发布

I want to learn using Ember.js for my next project. So far I have read the documentation here but I saw no explanation about Router. Then I read the guide here but I still don't understand how to use Router properly. I tried using Router this way, I want 2 route:

  1. /login which displays a button to enter the second route
  2. /home which displays a button to enter the first route

This is just a very simple code to test using Router to switch between "pages". I tried using this code but all I get is a blank page:

<script src="js/libs/jquery-1.7.2.min.js"></script>
<script src="js/libs/handlebars-1.0.0.beta.6.js"></script>
<script src="js/libs/ember-1.0.pre.min.js"></script>
<script>
    var App = Ember.Application.create();

    App.ApplicationController = Ember.Controller.extend();
    App.ApplicationView = Ember.View.extend();

    App.LoginView = Ember.View.extend({
        templateName: 'login-page'
    });

    App.HomeView = Ember.View.extend({
        templateName: 'home-page'
    });

    App.router = Ember.Router.create({
        enableLogging: true,
        root: Ember.Route.extend({
            index: Ember.Route.extend({
                route: '/',
                redirectsTo: 'login'
            }),
            login: Ember.Route.extend({
                route: '/login',
                doLogin: Ember.Route.transitionTo('home'),
                connectOutlets: function (router) {
                    router.get('applicationController').connectOutlet('login');
                }
            }),
            home: Ember.Route.extend({
                route: '/home',
                doLogout: Ember.Route.transitionTo('login'),
                connectOutlets: function (router) {
                    router.get('applicationController').connectOutlet('home');
                }
            })
        })
    });
    App.initialize(App.router);
</script>

<script type="text/x-handlebars" data-template-name="login-page">
    <h1>Login Page</h1>

    <button {{action doLogin}}>Login</button>
</script>

<script type="text/x-handlebars" data-template-name="home-page">
    <h1>Home Page</h1>

    <button {{action doLogout}}>Logout</button>
</script>

When I run this, the URL goes to #/login but it display nothing. Does anyone can show me how to make the above code works? Why do I get a blank page?

1条回答
【Aperson】
2楼-- · 2019-05-07 11:43

Your code: http://jsfiddle.net/jPn3H/

...updated with a brand new 'application' template hooked up to App.ApplicationView: http://jsfiddle.net/pauldechov/jPn3H/1/

The .initialize() function appends App.ApplicationView to <body> for you. Those .connectOutlet(...) calls won't do much of anything unless there's an {{outlet}} to connect. Hope that helps.

查看更多
登录 后发表回答