我正在尝试使用多个动态页面创建一个简单的应用程序:index,about和contact。我不想硬编码路由器中的路由;用户可以在不必编辑路由器的情况下添加页面。我从Ember-cli开始。
我在网上找到了一个简要介绍此任务的教程:http://mavilein.github.io/javascript/2013/09/28/three-steps-to-ember-js-seo-friendly-urls/。不幸的是,在使用Ember Data时,我可以解决两个主要问题:
this.store.find("page", params["page_id"]);
返回san数组,而不是对象。它实际上不是为检索单个对象而设计的。
永远不会调用serialize
上的Route
函数。
适配器
import DS from 'ember-data';
export default DS.FixtureAdapter.extend({
queryFixtures: function(fixtures, query, type) {
var key = Ember.keys(query)[0];
return fixtures.filterBy(key, query[key]); //This must be an array, not an object.
}
});
模型
import DS from "ember-data";
var Page = DS.Model.extend({
title: DS.attr(),
body: DS.attr()
});
Page.reopenClass({
FIXTURES: [
{
id: 1,
title: "Contact",
body: "Aenean lacinia bibendum nulla sed consectetur. Curabitur blandit tempus porttitor. Maecenas faucibus mollis interdum. Maecenas sed diam eget risus varius blandit sit amet non magna.",
path: "contact"
},{
id: 2,
title: "About",
body: "Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Curabitur blandit tempus porttitor. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.",
path: "about"
}
]
});
export default Page;
路由器
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.resource("page", {"path": "/:page_id"});
});
export default Router;
路线(页面)
import Ember from "ember";
export default Ember.Route.extend({
model: function(params) {
return this.store.find("page", {"path": params["page_id"]});
},
serialize: function() {
alert("serialize"); //is never called
}
});
模板
{{title}} //Must be wrapped in {{#each}} in order to loop through the array of a single object
我实际做这项工作的唯一方法是将整数id
更改为与URL匹配的字符串。这种方法感觉它正在摧毁模型;我认为这不是正确的方法。
答案 0 :(得分:1)
find()
应该总是返回一个数组,然后调用findQuery()
。尽管你可以获得第一个并在新的承诺中返回它,但这并不重要:
export default Ember.Route.extend({
model: function(params) {
var query = this.store.find("page", { path: params.page_id });
var promise = new Ember.RSVP.Promise(function(resolve, reject) {
query.then(function(result) {
resolve(result.get('firstObject'));
},
function(err) {
reject(err);
});
});
return promise;
},
});
仅调用序列化以从模型中获取参数,因此仅限于{{link-to 'page'}}