我正在尝试构建一个从表单收集信息的简单 Ember 应用程序。我正在使用 this tutorial作为指南。在本教程中,它具有以下代码以从表单中获取信息:
export default Ember.Component.extend({
...
actions: {
saveRental1() {
var params = {
owner: this.get('owner'),
city: this.get('city'),
type: this.get('type'),
image: this.get('image'),
bedrooms: this.get('bedrooms'),
};
...
this.sendAction('saveRental2', params);
}
}
});
这里是一些相关的表单代码:
<div class="form-group">
<label for="image">Image URL</label>
{{input value=image id="image"}}
</div>
<button {{action 'saveRental1'}}>Save</button>
</form>
在我的解决方案中,我无法让它工作。 this.get('whatever') 在我的代码中总是显示为“未定义”。经过一些调试后,我找到了解决方案,但这意味着将我的代码从 this.get('city')
更改为 this.controller.get('city')
有人可以解释我做错了什么或为什么吗?使用 this.controller 是“标准”吗?
最佳答案
模板上下文将成为 Controller 。 Route model
hook返回数据默认会通过setupController
设置在controller model
属性中。您可以通过 this.controller
路径访问 Controller 。
如果您在组件内部使用 this
它将引用组件实例,在您的情况下,如果您在组件中获得了 city
属性,那么您可以访问它在组件中使用 this.get('city')
。
关于javascript - 在 Ember 中,this 和 this.controller 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45617580/