骨干路由器只在第一次触发,重新提交后不工作?

时间:2015-07-08 15:17:35

标签: javascript backbone.js backbone-routing

所有

我正在使用路由器" #search"开始从另一个视图启动集合提取。

**Router code**

    // DesktopRouter.js
    // ----------------
    define(["jquery", "backbone", "views/Page", "views/Form", "views/Results"],

        function ($, Backbone, Page, Form, Results)
        {

            var DesktopRouter = Backbone.Router.extend({

                initialize: function ()
                {

                    // Tells Backbone to start watching for hashchange events
                    Backbone.history.start();

                },

                // All of your Backbone Routes (add more)
                routes: {

                    // When there is no hash on the url, the home method is called
                    "": "index",
                    "search": "search"

                },

                index: function ()
                {
                    console.log("Loading index");
                    // Instantiates a new view which will render the header text to the page
                    new Page();
                    new Form();

                },


                search: function ()
                {
                    console.log("Loading search results view : " + selectedTrade);
                    var selectedTrade = $("#tradesField").val();

                    new Results(selectedTrade) //pass this value to the view which in turn passes to collection to pass in GET

                }

...

表格

采取行动" #search"

 <div class="col-md-3" id="form">
            <p class="lead">Search for Tradesmen</p>
            <div class="form-group">
                <form action="#search">
                    <input id="tradesField" type="text" class="form-control">
                    <input id="searchTrades" type="submit" value="Search" class="btn btn-default form-control" />

                </form>


            </div>
        </div>

第一次提交表单时,工作正常。但是我无法在第一次之后重新提交查询并触发功能。我必须不断刷新页面并删除#search标记。

如何让每个表单提交都能正常工作?

1 个答案:

答案 0 :(得分:1)

The route events occur only when the hash actually changes. The first time you submit the form, the hash becomes #search, and triggers the router's route:search event. However, the second time you submit the form (assuming you didn't navigate somewhere else beforehand), the hash is already #search, so there is no event triggered.

I've never seen a form with a hash as its action handler, but I don't think you'll be successful doing it this way. You're probably going to need some sort of view bound to that element, like so:

var Search = Backbone.View.extend({
   el: '#id-of-my-form-element',
   events: { 'submit' : 'onSubmit' },
   onSubmit: function(e){
      router.navigate('search', { trigger: true });
   }
})

var search = new Search;

You should also add the search query into the hash, like #search?q=someQuery, so that the back button has its expected behavior.