kab*_*bal 10 javascript ember.js
我想在emberjs中定义一个路由,它有一个可选参数,例如:
/video
和
/video/123
如果没有提供参数,我想使用默认的模型/夹具.如果提供了参数,那么我想显然使用参数查找模型.
如果我然后去不同的路线,并返回没有参数的路线,我想使用以前加载的模型.
例如:
startup app
/video - 显示我的默认/夹具模型
/video/123 - 显示模型123
/another-route - 显示新路线
/video - 显示模型123
这可能吗?
我最终使用了不同的解决方案:
this.resource('video', function() {
this.route('index', {path: '/'});
this.route('item', {path: ':id'});
});
Run Code Online (Sandbox Code Playgroud)
这些路线支持:
/video - 显示我的默认/夹具模型
/video/123 - 显示模型123
当用户访问时/video,VideoIndexRoute必须重定向到没有任何id的VideoItemRoute.
var VideoIndexRoute = Em.Route.extend({
afterModel: function() {
// this is the tricky part
this.replaceWith('video.item', '');
}
});
Run Code Online (Sandbox Code Playgroud)
现在,VideoItemRoute必须检查是否有任何关联的模型,当它丢失时,它应该使用默认固定装置或新固定装置.
var VideoItemRoute = Em.Route.extend({
model: function(param) {
if (param.id) {
return this.store.find('video', param.id);
}
},
setupController: function (controller, model) {
if (!model) {
model = this.store.createRecord('video',{
name: 'default Name'
});
// or use fixture...
}
this._super(controller, model);
}
});
Run Code Online (Sandbox Code Playgroud)
有一种干净的方法可以做到这一点,虽然它有点"棘手".我们的想法是使用嵌套路由来保存id,但不渲染它,而是让父路由负责使用渲染助手来渲染它.当你这样做时,所有逻辑都可以存在于VideoChoiceController中,它将用于显示默认视频或特定视频.这样做的时候,没有必要明确地"记住"最后一个视频,路由引擎代表的状态机为你做了.
App.Router.map(function) {
this.resource('video', function(){
this.route('choice', {path: ':video_id'});
});
});
App.VideoRoute = Ember.Route.extend({
model: function(params) {
return App.get('defaultVideo');
},
setupController: function(controller, model) {
var video_choice = this.controllerFor('video.choice')
// this is necessary if you want, for example,
// to display the name or a link to the default video
// when a specific video is being displayed
controller.set('model', model);
if(Ember.isEmpty(video_choice.get('model'))){
video_choice.set('model', model);
}
}
});
App.VideoChoiceRoute = Ember.Route.extend({
model: function(params) {
return this.get('store').find('video', params.video_id);
},
renderTemplate: function() {
// if you don't override renderTemplate to do nothing,
// everything will still work but you will get an assertion
// error that render should only be used once with a
// singleton controller
}
});
<script type="text/x-handlebars">
<div>
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" data-template-name='video'>
<div> attrributes here always refer to the default video: {{name}} </div>
{{render "video.choice"}}
</script>
<script type="text/x-handlebars" data-template-name='video'>
<div>
attrributes here always refer to specific or last video,
or default if a specific video has never been loaded: {{name}}
</div>
</script>
Run Code Online (Sandbox Code Playgroud)