2

SPA アプリケーションに backbone.js を使用しており、JQuery UI オートコンプリート ウィジェットを含める必要があります。

モデル

define(['underscore', 'backbone'], function(_, Backbone) 
{
   var Consumer = Backbone.Model.extend
   ({   
        initialize: function()
        {
        },
        toJSON: function() 
        {
            var data;

            var json = Backbone.Model.prototype.toJSON.call(this);

            _.each(json, function(value, key) 
            {
                 data = key;
            }, this);

            return data;
        }   
    });

    return Consumer;
});

コレクション

define(['jquery', 'underscore', 'backbone', 'models/consumer'], function($, _, Backbone, Consumer)
{
    var Consumers = Backbone.Collection.extend
    ({
          model: Consumer,
          url: 'http://localhost/test',

          initialize: function()
          {
          }
    });

    return new Consumers;
});

意見

define(['jquery', 'underscore', 'backbone', 'text!templates/home.html', 'collections/consumers', 'jqueryui'], function($, _, Backbone, homeTemplate, Consumers)
{
      var HomeView = Backbone.View.extend
      ({
             el: $("body"),

             initialize: function()
             {
                  this.collection = Consumers;

                  this.collection.fetch(({async: false}));
             },
             events: 
             {
                  'focus #consumer': 'getAutocomplete',
             },
             render: function(options)
             {          
                  this.$el.html(homeTemplate);
             },
             getAutocomplete: function () 
             {
                  $("#consumer").autocomplete(
                  {
                        source: JSON.stringify(this.collection),
                  });
             }
    });

    return new HomeView;
 });

問題は、ユーザーが入力中に autosuggest が奇妙な GET リクエストを送信することです。

collection.fetch() 

コレクションに次の JSON 配列を入力します。

["11086","11964","14021","14741","15479","15495","16106","16252"]

ユーザーがオートコンプリート (たとえば 15) に入力し始めると、次の GET 要求が送信されます。

http://localhost/test/%5B%2211086%22,%2211964%22,%2214021%22,%2214741%22,%2215479%22,%2215495%22,%2216106%22,%2216252%22%5D?term=15

私のコードの問題は何ですか?

4

1 に答える 1

3

オートコンプリートのソース オプションに関する jQuery UI API ドキュメントから:

String : 文字列が使用される場合、オートコンプリート プラグインは、その文字列が JSON データを返す URL リソースを指していると想定します。

あなたがするとき

$("#consumer").autocomplete({
  source: JSON.stringify(this.collection),
});

文字列を指定すると、オートコンプリートは URL を指定していると認識し、代わりに配列を指定します。

$("#consumer").autocomplete({
  source: this.collection.toJSON();
});

ただし、モデルのプロパティが必要labelですvalue

私がお勧めするのは、コレクションに別の関数を作成することです

getSuggestions: function() {
  // returns an array of strings that you wish to be the suggestions for this collection
}

代わりにそれを使用します:

$("#consumer").autocomplete({
  source: this.collection.getSuggestions();
});
于 2012-10-15T10:46:43.703 に答える