EmberJS如何处理transitionTo
当输入搜索查询并按下回车按钮或单击提交按钮时,我有以下代码调用transitionToRoute(’search’)。
但是,我的路由器仍然不会在模板中显示searchQuery:
You searched for: "{{searchQuery}}"
搜索某些内容时,url看起来像http://www.example.com/#/search/[object Object]
(这对我来说似乎不对)。
(完整代码可以在以下url查看: http : //jsfiddle.net/Mn2yy/1/ )这是相关代码:
模板:
{{view Ember.TextField valueBinding="search" action="doSearch"}} {{outlet}} Search
{{#linkTo "home"}}Homepage{{/linkTo}} You searched for: "{{searchQuery}}"
应用控制器:
MyApp.ApplicationController = Ember.Controller.extend({ // the initial value of the `search` property search: '', doSearch: function() { // the current value of the text field var query = this.get('search'); this.transitionToRoute('search'); } });
和Searchpage路线:
MyApp.SearchRoute = Ember.Route.extend({ setupController: function(controller) { controller.set('searchQuery', this.get('query')); }, renderTemplate: function() { this.render('searchpage', { into: 'container' }); } });
首先,您需要在路由器中为搜索路径定义动态段:
MyApp.Router.map(function() { this.route("home", { path: "/" }); this.route("search", { path: "/search/:query" }) });
然后在doSearch
操作中在应用程序上设置searchQuery
属性。 您还将query
变量传递给transitionToRoute
方法,因为它将填充动态段。
MyApp.ApplicationController = Ember.Controller.extend({ // the initial value of the `search` property search: '', doSearch: function() { // the current value of the text field var query = this.get('search'); this.set('searchQuery', query); this.transitionToRoute('search', query); } });
由于您需要从App.SearchController
实例访问此属性,因此您需要使用needs
API将2个控制器连接在一起:
MyApp.SearchController = Ember.Controller.extend({ needs: ['application'], application: Ember.computed.alias('controllers.application') });
将controllers.application
属性别名化为application
,以避免过多的输入,例如。 在模板中。
然后在search
模板中绑定到此属性:
最后一步:如果此时刷新页面,则不会从URL自动填充searchQuery
。 让我们用deserialize
钩子解决这个问题:
MyApp.SearchRoute = Ember.Route.extend({ deserialize: function(params) { this.controllerFor('application').setProperties({ searchQuery: params.query, search: params.query }); }, renderTemplate: function() { this.render('searchpage', { into: 'container' }); } });
这将从URL获取params并使用query
键的值设置应用程序控制器。
这就是它,希望我没有错过任何东西!