javascript - Should I and how to transitionToRoute in a promise callback -
in ember controller, want call api create user , on success, transitiontoroute. want work:
import ajax "ic-ajax"; import ember "ember"; export default ember.controller.extend({ actions: { createandloginuser: function() { var user = { "user": this.getproperties("email", "name") }; ajax({ url: "api/users", type: "post", data: user }) .then(transitiontohome); } } }); var transitiontohome = function() { this.transitiontoroute("home") }
but when place debugger
in method, this
no longer controller object , out of scope call transitiontoroute
.
i've ever written hacky javascript, i'm trying learn core concepts , frameworks. right way use promise? , right place in ember put transition?
your problem has nothing ember or transitions; it's this
handling. simplest solution just
.then(transitiontohome.bind(this));
putting transition method inside controller
you consider putting transitiontohome
inside controller method. then, call in following:
export default ember.controller.extend({ transitiontohome: function() { this.transitiontoroute("home"); }, actions: { createandloginuser: function() { var self = this; var user = { "user": this.getproperties("email", "name") }; ajax({ url: "api/users", type: "post", data: user }) .then(function() { self.transitiontohome(); }); } } });
this might simpler approach more readable , doesn't require reasoning this
, using bind
(but require using self
).
moving transition route?
outside scope of question, route-related logic (including transitioning) logically belongs in route, not controller. if agree, refactor above send
createandloginuser: function() { var user = { "user": this.getproperties("email", "name") }; var self = this; ajax({ url: "api/users", type: "post", data: user }) .then(function() { self.send("gohome"); }); } }
and implement gohome
action in route. or, implement gohome
in higher-level route, application route, making available controller or lower-level route.
moving ajax logic service?
others might ajax logic not belong here in controller, , should rightfully in services layer, so
// services/user.js export function createuser(data) { return ajax({ url: "api/users", type: "post", data: { user: data } }); } // controller import { createuser } 'app/services/user'; export default ember.controller.extend({ createandloginuser: function() { var data = this.getproperties("email", "name")); var self = this; createuser(data) . then(function() { self.send("gohome"); }); } };
using es6 syntax, can avoid self
, simplifying bit in process:
createandloginuser: function() { var data = this.getproperties("email", "name")); var gohome = () => this.send("gohome"); createuser(data) . then(gohome); }
now code starting more semantic , readable.
Comments
Post a Comment