当 promise 成功并且我尝试使用 this.set('propertyName', value) 设置 Controller 的属性
时,我收到有关 set 方法的以下错误:
TypeError: undefined is not a function
模板:
<script type="text/x-handlebars">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Qlovi Reader</a>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<form class="navbar-form navbar-left" role="search"{{action 'updateInfo' on="submit" }}>
<div class="form-group">
{{input value=attemptQuestionSet type="text" class="form-control" placeholder="37297"}}
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
{{#if currentUser}}
<p class="navbar-text navbar-right">Signed in as {{currentUser.userName}}</p>
{{/if}}
</div>
</div>
</nav>
<div class="container-fluid">
{{outlet}}
</div>
</script>
应用程序 Controller :
App.ApplicationController = Em.Controller.extend({
currentQuestionSet: null,
actions:{
updateInfo: function(){
this.store.find('questionSet', parseInt(this.attemptQuestionSet)).then(function(questionSet){
this.set('currentQuestionSet',questionSet);
},function(){
alert("Question Set not found");
});
}
}
});
promise 成功后是否有新的范围或有关范围的其他问题?
最佳答案
一般来说,除非文档特别说明,否则您必须假设回调(不仅仅是 Promise,所有回调)都会丢失 this
指针的值。这种行为是因为调用者决定了 this
指向的内容,在本例中,调用者是 Ember 使用的任何 Promise 库中的 then
函数。
解决方案是在闭包中捕获 this
,如下所示:
App.ApplicationController = Em.Controller.extend({
currentQuestionSet: null,
actions:{
updateInfo: function(){
var self = this; // Store away current this
this.store.find('questionSet', parseInt(this.attemptQuestionSet)).then(function(questionSet){
self.set('currentQuestionSet',questionSet); // <-- note use of stored reference
},function(){
alert("Question Set not found");
});
}
}
});
关于javascript - Promise 成功后无法在 ember 中设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110420/