我使用控制器读取下拉菜单上选择的值,接受一些输入字段的参数,然后保存记录。它创建记录并接收信息。我的问题在于当我试图在动作结束时过渡到另一个页面时。我一直得到错误:Cannot read property 'transitionToRoute' of undefined
这是我的控制器代码:
var teamId;
export default Ember.Controller.extend({
auth: Ember.inject.service(),
actions: {
onSelectEntityType: function(value) {
console.log(value);
teamId = value;
return value;
},
createProcess: function(processName, processDescription) {
var currentID = this.get('auth').getCurrentUser();
let team = this.get('store').peekRecord('team', teamId);
let user = this.get('store').peekRecord('user', currentID);
let process = this.get('store').createRecord('process', {
team: team,
user: user,
name: processName,
description: processDescription
});
process.save().then(function () {
this.transitionToRoute('teams', teamId);
});
}
}
});
对应的路由如下:
export default Ember.Route.extend({
auth: Ember.inject.service(),
model: function() {
var currentID = this.get('auth').getCurrentUser();
return this.store.find('user', currentID);
}
});
你应该清楚地了解Javascript中的这个关键字。关键字this只取决于函数是如何被调用的,而不取决于它是如何/何时/在何处定义的。
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`
// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
请查看MDN文档以了解更多信息。
可以将this缓存到普通变量this中,然后在回调中访问。
var self = this;
process.save().then(function () {
self.transitionToRoute('teams', teamId);
});
ECMASCript 6引入了箭头函数,它的this是有词法作用域的。在这里,它就像一个普通变量一样在作用域中查找。
process.save().then(() => {
this.transitionToRoute('teams', teamId);
});