我正在尝试在ember.js中完成URL哈希上下文搜索。到目前为止,我已经远远地阅读了文档和观看教程,但现在我被卡住了。
问题:
当我访问/#/search/movie/bob
时,它检测到它应该搜索电影并在TMDB(电影数据库)API上执行查询并拉动电影。当我在浏览器的地址栏中将bob
更改为lord
时,路由会再次转换并执行搜索。当我在/search/:type/:query
状态下使用HTML搜索输入字段再次搜索时,会出现此问题。州政官员不会再次呼叫该路线。
这是我的路由器:
App.Router = Ember.Router.extend({
enableLogging: true,
root: Ember.Route.extend({
showSearchResults: Ember.Route.transitionTo('searchResults'),
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('search');
}
}),
searchResults: Ember.Route.extend({
route: '/search/:type/:query',
serialize: function(router, params) {
// App.SearchModel gets its values set by
// the bindAttr helper in the handlebar
// template
return {
type: App.SearchModel.get('type'),
query: App.SearchModel.get('inputValue')
}
},
connectOutlets: function(router, params) {
var type = null;
var query = null;
var searchController = router.get('searchController');
if (params && params.type && params.query) {
type = params.type;
query = params.query;
// make sure the SearchModel has its
// properties set to be able to display them
// properly in the search fields
App.SearchModel.set('type', type);
App.SearchModel.set('inputValue', query)
} else {
type = App.SearchModel.get('type');
query = App.SearchModel.get('inputValue');
}
// display the search bar again
router.get('applicationController').connectOutlet('search');
// perform a search against an API
searchController.search(type, query, function(data) {
router.get('applicationController').connectOutlet('search_results', 'searchResults', data);
});
}
})
})
});
以下是把手模板:
<script type="text/x-handlebars" data-template-name="search-view">
{% verbatim %}
<form class="form-inline">
{{view Ember.TextField valueBinding="App.SearchModel.inputValue" class="span7" placeholder="Search Movies - TV Shows ..." }}
<input type="hidden" {{bindAttr value="App.SearchModel.type"}} />
<button type="submit" class="btn btn-large" {{action showSearchResults on="click"}}>Search</button>
</form>
{% endverbatim %}
</script>
当您点击提交按钮时,只要您之前没有完成搜索,它就会调用showSearchResults
并进行转换。如果我处于初始/
状态,则会正确发生这种情况,但如果我处于/search/:type/:query
状态则不会。
我是否需要操纵哈希位置才能让它再次转换?或者是否有一种更好的惯用方式告诉ember当我点击搜索按钮时它应该更改:query
以便状态发生变化?
更新
我得到它的工作,但它感觉真的很hacky ..必须有一个更好的方法这样做?这是我的解决方案:
showSearchResults: function(router, e, b) {
// set the hash location so it knows to transition
// to searchResults correctly .. this feels very
// hacky ..
var hashLocation = Ember.HashLocation.create();
hashLocation.setURL('/search/%@/%@'.fmt(
App.SearchModel.get('type'),
App.SearchModel.get('inputValue')
));
router.location = hashLocation;
router.transitionTo('searchResults');
}