EmberJS : 동일한 경로에서 여러 모델을로드하는 방법은 무엇입니까?
저는 웹 개발에 익숙하지 않지만 클라이언트 측 MVC 프레임 워크에 익숙하지 않습니다. 나는 약간의 조사를했고 EmberJS와 함께하기로 결정했습니다. 나는 TodoMVC 가이드를 훑어 보았고 그것은 나에게 의미가있었습니다 ...
매우 기본적인 앱을 설정했습니다. 인덱스 경로, 두 모델 및 하나의 템플릿. 일부 db 행을 반환하는 서버 측 PHP 스크립트가 실행 중입니다.
저를 매우 혼란스럽게하는 한 가지는 동일한 경로에 여러 모델을로드하는 방법입니다. setupController 사용에 대한 정보를 읽었지만 아직 명확하지 않습니다. 내 템플릿에는 관련없는 db 행으로로드하려는 두 개의 테이블이 있습니다. 보다 전통적인 웹 앱에서는 SQL 문을 실행하고 행을 채우기 위해 루프를 반복했을 것입니다. 이 개념을 EmberJS로 번역하는 데 어려움이 있습니다.
동일한 경로에서 관련없는 데이터의 여러 모델을로드하려면 어떻게합니까?
최신 Ember 및 Ember 데이터 라이브러리를 사용하고 있습니다.
최신 정보
첫 번째 답변은 처리 방법을 제공하지만 두 번째 답변은 적절한 경우와 적절하지 않은 경우 다른 방법을 설명합니다.
Ember.RSVP.hash 를 사용하여 여러 모델을로드 할 수 있습니다 .
app/routes/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return Ember.RSVP.hash({
people: this.store.findAll('person'),
companies: this.store.findAll('company')
});
},
setupController(controller, model) {
this._super(...arguments);
Ember.set(controller, 'people', model.people);
Ember.set(controller, 'companies', model.companies);
}
});
템플릿 에서로드 된 데이터를 참조 people하고 companies가져올 수 있습니다 .
app/templates/index.js
<h2>People:</h2>
<ul>
{{#each people as |person|}}
<li>{{person.name}}</li>
{{/each}}
</ul>
<h2>Companies:</h2>
<ul>
{{#each companies as |company|}}
<li>{{company.name}}</li>
{{/each}}
</ul>
이 샘플이 포함 된 Twiddle입니다 : https://ember-twiddle.com/c88ce3440ab6201b8d58
주의 :
모델 후크에서 여러 모델을 반환하는 것이 적절한 지 여부에주의해야합니다. 이 간단한 질문을 스스로에게 물어보십시오.
- 내 경로가 슬러그를 사용하여 URL을 기반으로 동적 데이터를로드합니까
:id? 즉this.resource('foo', {path: ':id'});
예라고 대답했다면
해당 경로의 모델 후크에서 여러 모델을로드하지 마십시오 !!! 그 이유는 Ember가 경로 연결을 처리하는 방식에 있습니다. 해당 경로 ( {{link-to 'foo' model}}, transitionTo('foo', model))에 연결할 때 모델을 제공 하면 모델 후크를 건너 뛰고 제공된 모델을 사용합니다. 여러 모델을 예상했기 때문에 문제가 될 수 있지만 하나의 모델 만 제공됩니다. 다음은 대안입니다.
그것을에서 할 수있는 setupController/afterModel
App.IndexRoute = Ember.Route.extend({
model: function(params) {
return $.getJSON('/books/' + params.id);
},
setupController: function(controller, model){
this._super(controller,model);
controller.set('model2', {bird:'is the word'});
}
});
예 : http://emberjs.jsbin.com/cibujahuju/1/edit
전환을 차단해야하는 경우 (모델 후크처럼) 후크에서 promise를 반환합니다 afterModel. 해당 후크의 결과를 수동으로 추적하고 컨트롤러에 연결해야합니다.
App.IndexRoute = Ember.Route.extend({
model: function(params) {
return $.getJSON('/books/' + params.id);
},
afterModel: function(){
var self = this;
return $.getJSON('/authors').then(function(result){
self.set('authors', result);
});
},
setupController: function(controller, model){
this._super(controller,model);
controller.set('authors', this.get('authors'));
}
});
예 : http://emberjs.jsbin.com/diqotehomu/1/edit
아니오라고 대답했다면
계속해서 경로의 모델 후크에서 여러 모델을 반환 해 보겠습니다.
App.IndexRoute = Ember.Route.extend({
model: function() {
return {
model1: ['red', 'yellow', 'blue'],
model2: ['green', 'purple', 'white']
};
}
});
예 : http://emberjs.jsbin.com/tuvozuwa/1/edit
기다려야하는 경우 (예 : 서버 호출, 일종의 약속)
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
model1: promise1,
model2: promise2
});
}
});
예 : http://emberjs.jsbin.com/xucepamezu/1/edit
Ember Data의 경우
App.IndexRoute = Ember.Route.extend({
var store = this.store;
model: function() {
return Ember.RSVP.hash({
cats: store.find('cat'),
dogs: store.find('dog')
});
}
});
예 : http://emberjs.jsbin.com/pekohijaku/1/edit
하나는 약속이고 다른 하나는 그렇지 않은 경우 모두 좋습니다. RSVP는 해당 값을 기꺼이 사용합니다.
App.IndexRoute = Ember.Route.extend({
var store = this.store;
model: function() {
return Ember.RSVP.hash({
cats: store.find('cat'),
dogs: ['pluto', 'mickey']
});
}
});
예 : http://emberjs.jsbin.com/coxexubuwi/1/edit
믹스 앤 매치하고 재미있게 보내십시오!
App.IndexRoute = Ember.Route.extend({
var store = this.store;
model: function() {
return Ember.RSVP.hash({
cats: store.find('cat'),
dogs: Ember.RSVP.Promise.cast(['pluto', 'mickey']),
weather: $.getJSON('weather')
});
},
setupController: function(controller, model){
this._super(controller, model);
controller.set('favoritePuppy', model.dogs[0]);
}
});
예 : http://emberjs.jsbin.com/joraruxuca/1/edit
Marcio가 제공 한 대답과 같은 것을 사용하지만 다음과 같이 보입니다.
var products = Ember.$.ajax({
url: api + 'companies/' + id +'/products',
dataType: 'jsonp',
type: 'POST'
}).then(function(data) {
return data;
});
var clients = Ember.$.ajax({
url: api + 'clients',
dataType: 'jsonp',
type: 'POST'
}).then(function(data) {
return data;
});
var updates = Ember.$.ajax({
url: api + 'companies/' + id + '/updates',
dataType: 'jsonp',
type: 'POST'
}).then(function(data) {
return data;
});
var promises = {
products: products,
clients: clients,
updates: updates
};
return Ember.RSVP.hash(promises).then(function(data) {
return data;
});
Ember Data를 사용하면 관련없는 모델에 대해 더 간단 해집니다.
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller,model);
var model2 = DS.PromiseArray.create({
promise: this.store.find('model2')
});
model2.then(function() {
controller.set('model2', model2)
});
}
});
If you only want to retrieve an object's property for model2, use DS.PromiseObject instead of DS.PromiseArray:
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller,model);
var model2 = DS.PromiseObject.create({
promise: this.store.find('model2')
});
model2.then(function() {
controller.set('model2', model2.get('value'))
});
}
});
The latest version of JSON-API as implemented in Ember Data v1.13 supports bundling of different resources in the same request very well, if you don't mind modifying your API endpoints.
In my case, I have a session endpoint. The session relates to a user record, and the user record relates to various models that I always want loaded at all times. It's pretty nice for it all to come in with the one request.
One caveat per the spec is that all of the entities you return should be linked somehow to the primary entity being received. I believe that ember-data will only traverse the explicit relationships when normalizing the JSON.
For other cases, I'm now electing to defer loading of additional models until the page is already loaded, i.e. for separate panels of data or whatever, so at least the page is rendered as quickly as possible. Doing this there's some loss/change with the "automatic" error loading state to be considered.
참고URL : https://stackoverflow.com/questions/20521967/emberjs-how-to-load-multiple-models-on-the-same-route
'program story' 카테고리의 다른 글
| C #에서 절대 경로에 대한 상대 경로? (0) | 2020.10.20 |
|---|---|
| node.js에서 로그인 인증을 구현하는 방법 (0) | 2020.10.20 |
| ES6를 사용한 VS 코드 (0) | 2020.10.20 |
| Spring Security에서 'X-Frame-Options'응답 헤더를 비활성화하는 방법은 무엇입니까? (0) | 2020.10.20 |
| RecyclerView 가로 스크롤 스냅 중앙 (0) | 2020.10.20 |