1

我有以下代码,当输入搜索查询并按下输入按钮或单击提交按钮时,它会调用 transitionToRoute('search') 。

但是,我的路由器仍然不会在它说的模板中显示 searchQuery:

<p>You searched for: "{{searchQuery}}"</p>

http://www.example.com/#/search/[object Object]并且 URL在搜索某些东西时看起来像(这对我来说似乎不正确)。

(完整代码可以查看:http: //jsfiddle.net/Mn2yy/1/)这是相关代码:

模板:

<script type="text/x-handlebars" data-template-name="container">
    <button {{action "doSearch"}} rel="tooltip-bottom" title="search" class="icon"><i class="icofont-search"></i></button>
    {{view Ember.TextField valueBinding="search" action="doSearch"}}

    {{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="searchpage">
    <h1>Search</h1>
    {{#linkTo "home"}}Homepage{{/linkTo}}
    <p>You searched for: "{{searchQuery}}"</p>
</script>

应用控制器:

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' });
    }
});
4

1 回答 1

4

首先,您需要在路由器中为搜索路由定义动态段:

MyApp.Router.map(function() {
    this.route("home", { path: "/" });
    this.route("search", { path: "/search/:query" })
});

然后在操作中设置searchQuery应用程序的属性doSearch。您还将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实例访问此属性,因此您需要使用needsAPI 将 2 个控制器连接在一起:

MyApp.SearchController = Ember.Controller.extend({
    needs: ['application'],
    application: Ember.computed.alias('controllers.application')
});

controllers.application属性别名为 just application,以避免输入过多,例如。在模板中。

search然后在模板中绑定到这个属性:

<script type="text/x-handlebars" data-template-name="searchpage">
    <h1>Search</h1>
    {{#linkTo "home"}}Homepage{{/linkTo}}
    <p>You searched for: "{{application.searchQuery}}"</p>
</script>

最后一步:如果此时刷新页面,searchQuery不会自动从 URL 填充。让我们用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 获取参数并使用query键的值设置应用程序控制器。

差不多就这些了,希望没有遗漏!

于 2013-04-15T13:18:35.577 回答