2013-10-29 40 views
0

ember.js的新手段。我想要做的是:创建一个没有路径的过渡路由,当我转换到模型时,我可以将AJAX承诺作为模型传递,然后在承诺完成后做出重定向决策。我希望在发生这种情况时调用LoadRoute视图。我试图实现与下列路线:Ember.js:无路径过渡路线

App.LoginUserRoute = Ember.Route.extend({ 
    setupController: function(controller, model) { 
     //Model should be a promise 
     model.then(this.success.bind(this),this.failure.bind(this)); 
    }, 

    success: function (data) { 
     if (data.success) { 
      App.loggedInUser = App.User.create(data); 
      console.log(App.loggedInUser); 
      //Make redirection decision 
     } 
     else { 
      alert(data.error); 
     } 
    }, 

    failure: function() { 
     //Failure code 
    } 
}); 

然而,当我尝试的承诺传递到路线类似如下:

var request = $.post("api.php", {action: 'create_user', username: this.username, password: this.password}); 
this.transitionToRoute('loginUser',request); 

我得到的错误“更多的上下文对象是传递比路由的动态段:loginUser“,因为我试图创建无路径路由,并且Ember要求在使用transitionToRoute()传递时将模型序列化到路径中。

的原因,我需要的是这样的:

  • 登录事件可以从多个控制器(当用户注册碰巧,当他们登录使用的登录屏幕,或者当应用程序首次加载如果有合适的cookie是检测到),我不想在所有这些控制器上重复登录逻辑。
  • 登录完成后,根据返回的用户对象的性质,可以将多个不同的路由导向到用户对象。
  • 我希望在请求完成时调用LoadRoute。

我假设我的问题的解决方案不是使用路由,而是其他的东西。但是,我不确定什么是“别的东西”。

回答

0

最后我取得了什么,我试图通过添加以下代码ApplicationController中

loginUser: function (request) { 
    this.transitionToRoute('loading'); 
    request.then(this.loginRequestSuccess.bind(this),this.loginRequestFailure.bind(this)); 
}, 

loginRequestSuccess: function (data) { 
    if (data.success) { 
     App.loggedInUser = App.User.create(data.user); 
     console.log(App.loggedInUser); 
     //Route transition decision 
    } 
    else { 
     alert(data.error); 
    } 
}, 

loginRequestFailure: function() { 
    //Failure code 
} 

做然后从代码中的任何地方使用jqXHR对象调用loginUser()函数进行登录请求。

1

你会想要利用mixin,并挂钩到转换路线。

以下SO答案将您所有的工作需求:

Ember Client Side Authentication, route authentication

+0

我不明白这是如何处理我的问题,有多种方式让用户登录(通过注册,登录或cookie,每种方式触发不同类型的api请求到api。 )我需要一些可以传递jqXHR或承诺的东西,让它调用LoadRoute,然后在jqXHR/promise完成后做出路由重定向决定。 – AlliterativeAlice

+0

但+1因为我不知道这个功能,它会派上用场。 – AlliterativeAlice