使用ember.js在子视图之间切换?

时间:2012-11-19 08:21:07

标签: ember.js

我正在尝试渲染一个在两个孩子之间切换的视图(或者我希望如此)并且某些东西并不完全正常。这是我的模板:

{{#view App.LoginFormView isVisibleBinding="user.isNotAuthenticated" }}
Username: {{view Ember.TextField valueBinding="user.loginName"}} / 
Password: {{view Ember.TextField valueBinding="user.userPassword" type="password"}}
<button class="btn" {{ action "login" }} {{bindAttr disabled="user.isNotValid"}}>Login</button>
{{/view}}

{{#view App.LoginInfoView isVisibleBinding="user.isAuthenticated" }}
You are logged in as {{user.loginName}}. Click <a {{action "logout"}}>here</a> to logout
{{/view}}
app.js中的

我有以下内容:

App.User = Ember.Object.extend({
    loginName:'',
    userPassword:'',
    rememberMe:true,
    isNotValid:function(){
        return (this.get("loginName") == '') || (this.get("userPassword") == '');
    }.property('loginName', 'userPassword'),
    isAuthenticated:false,
    isNotAuthenticated:function(){
        return !this.isAuthenticated;
    }.property('isAuthenticated')
});

App.AuthenticationController = Ember.Controller.extend({
    login:function() {
        alert("loginName:"+this.user.get('loginName')+";\n"+
              "userPassword:"+this.user.get('userPassword')+";\n"+
          "rememberMe:"+this.user.get('rememberMe')+";\n");
        this.user.isAuthenticated = true;
    },
    user:App.User.create()
});
App.AuthenticationView = Ember.View.extend({
    templateName: 'authentication',
    userBinding:"App.AuthenticationController.user"
});

App.LoginFormController = Ember.Controller.extend({
    userBinding:"App.AuthenticationController.user"
});
App.LoginFormView = Ember.View.extend();

App.LoginInfoController = Ember.Controller.extend({
    userBinding:"App.AuthenticationController.user"
});
App.LoginInfoView = Ember.View.extend();

App.Router = Ember.Router.extend({
    enableLogging:true,
    root: Ember.Route.extend({
        index: Ember.Route.extend({
            route: '/',
            connectOutlets: function(router){
                router.get('applicationController').connectOutlet('authentication','authentication');
            },
            login:function(router){
                router.get('authenticationController').login();
            }
        })
    })
});

我遇到的问题是视图没有切换isAuthenticated属性的更改。我的印象是自动发生,但事实并非如此。关于如何使这项工作的任何想法?或者我错过了一些基本的东西(这里是ember.js新手,所以要温柔: - ))

干杯, 亚历克斯。

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式实施用户身份验证:

在您的模板中(例如_header.hbs模板中application.hbs的部分模板)

{{#if needAuth}}
    // login form goes here
    <button {{action submitLogin}}>login</button>
{{else}}
    <small {{action logout}}>logout</small>
{{/if}}

在应用程序控制器中:

submitLogin: function () {
    // do login stuff

    // if login success
    that.set('needAuth', false);
    // else
    that.set('needAuth', true);
});

DOM会自动更新。在其他部分模板中,您也可以使用{{#if needAuth}}