[英]How to access Emberjs Model Data inside a Route
I would like to access all data of say a ( Message
model with value
and author
properties) inside a route or controller, do something with them, and then store them to an HTML localStorage. 我想访问路由或控制器中的所有数据(例如具有
value
和author
属性的Message
模型),对它们进行处理,然后将其存储到HTML localStorage。 However, all of the examples I have seen so far use each controller
to access every model data on Handlebars. 但是,到目前为止,我看到的所有示例都使用
each controller
来访问车把上的每个模型数据。 The following is my pseudo-implementation. 以下是我的伪实现。
App.MessagesRoute = Ember.Route.extend({
setupController: function(controller, model) {
messages = this.get('store').find('message')
//^This returns a PromiseArray but I can't seem to access the actual values.
//I also tried messages.forEach but it doesn't seem to work
//...
//...
//Below is what I'd like to do, to push the messages into the localStorage
//Therefore I'd like `messages` to be an array
for (var i=0; i<messages.length; i++)
localStorage.setItem('messages', JSON.stringify(messages[i]))
}
});
I know I'm just missing something simple here. 我知道我只是在这里缺少一些简单的东西。 But I just couldn't find it on the docs.
但是我只是在文档中找不到它。
Any help would be much appreciated. 任何帮助将非常感激。
You just need to wait for the promise array to fulfill and then iterate over it like this: 您只需要等待promise数组完成,然后像这样遍历它即可:
App.MessagesRoute = Ember.Route.extend({
setupController: function(controller, model) {
messages = this.get('store').find('message')
messages.then(function() {
messages.forEach(function(message) {
// do what ya like
});
});
});
See the PromiseArray docs and forEach docs . 请参阅PromiseArray文档和forEach文档 。
The Ember way is to first setup the model in your route and Ember will only call setupController after the promise has resolved (ie after the model(s) have been fetched). Ember方式是先在您的路线中设置模型,Ember仅在兑现承诺后(即在获取模型之后)才会调用setupController。
App.MessagesRoute = Ember.Route.extend({
model: function() {
return this.get('store').find('message');
},
setupController: function(controller, model) {
model.forEach(function(msg) {
// save message to localStorage here
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.