如何使用Backbone.js正确添加jQuery UI自动完成小部件

时间:2012-03-12 07:56:08

标签: javascript jquery-ui backbone.js

我正在学习Backbone.js。我目前假设如果使用Backbone.js,那么所有客户端javascript / jQuery都应该与Backbone集成。从各种在线教程中,我可以看到Backbone如何工作并理解其基本原理。

但是jQuery UI小部件呢?这些也应该与Backbone.js集成吗?例如,我想在表单字段上使用jQuery UI Autocomplete小部件(请参阅下面的代码)。我将如何使用Backbone.js进行此操作(或者不使用Backbone进行此类操作)?看起来像Backbone'Model'和'Collection'不适用于jQuery Autocomplete Widget,因为这种东西被绑定在jQuery UI Widget本身中。

(function($){

  $(document).ready(function() {
    $(this.el).autocomplete({
      source: function(req, res) {
        $.ajax({
          url: '/orgs.json?terms=' + encodeURIComponent(req.term),
          type: 'GET',
          success: function(data) { 
            res(data); 
          },
          error: function(jqXHR, textStatus, errorThrown) {
            alert('Something went wrong in the client side javascript.');
          },
          dataType: 'json',
          cache: false
        });
      }
    });
  });

})(jQuery);

此类事情的标准做法是什么?我唯一能想到的是创建一个视图,然后在渲染功能中添加小部件。但这对我来说似乎并不是非常的主干。

4 个答案:

答案 0 :(得分:7)

在我看来,使用this.collection访问包含数据的集合,就像@saniko一样,我在视图的render函数中设置了自动完成功能:

render : function() {
    ...

    var me = this; //Small context issues

    this.$el.find('input.autocompleteSearch').autocomplete({
        source : function(request, response){
            me.collection.on('reset', function(eventname){
                var data = me.collection.pluck('name');
                response(data); //Please do something more interesting here!
            });

            me.collection.url = '/myresource/search/' + request.term;
            me.collection.fetch();
        }
    });

    ...
},  
...

答案 1 :(得分:4)

渲染视图时附加所有插件:

你可以这样做:

render: function () {

  var view = this;
  // Fetch the template, render it to the View element and call done.

  application_namespace.fetchTemplate(this.template, function (tmpl) {
    var viewModel = view.model.toJSON();
    view.$el.html(tmpl(viewModel));

    view.$("#categories").autocomplete({
      minLength: 1,
      source: function (request, response) {
        $.getJSON("url" + view.storeId, {
            term: request.term,
          }, function (data) {
            response($.map(data, function (item) {
              return {
                value: item.title,
                obj: item
              };
          }));
        });
      },

      select: function (event, ui) {
        //your select code here
        var x = ui.item.obj;
        var categories = view.model.get("x");

        // bla bla
      }
      error: function (event, ui) {
        //your error code here
      }
    }
  });
}

希望有所帮助

答案 2 :(得分:3)

我正在使用自动填充来增强许多表单视图中的“位置”字段,这些视图与不同的模型和不同的搜索API进行交互。

在这种情况下,我觉得“自动完成局部性”是该字段的“行为”,而不是视图本身并保持干燥我以这种方式实现它:

  • 我有一个LocalityAutocompleteBehavior实例
  • 我通过将行为应用于他们想要的表单字段
  • 来使用此实例
  • 行为将“jquery-ui autocomplete”绑定到表单字段,然后在自动完成发生时在视图模型中创建属性,然后视图可以对这些字段执行任何操作。

这是一些coffeescript摘录(我也在https://github.com/jrburke/jqueryui-amd使用requirejs和令人敬畏的jquery-ui amd包装器)

LocalityAutocompleteBehavior:

define [
  'jquery'
  #indirect ref via $, wrapped by jqueryui-amd
  'jqueryui/autocomplete'
], ($) ->
  class LocalityAutocompleteBehavior

    #this applies the behavior to the jQueryObj and uses the model for 
    #communication by means of events and attributes for the data
    apply: (model, jQueryObj) ->
      jQueryObj.autocomplete
        select: (event, ui) ->
          #populate the model with namespaced autocomplete data 
          #(my models extend Backbone.NestedModel at 
          # https://github.com/afeld/backbone-nested)
          model.set 'autocompleteLocality',
            geonameId: ui.item.id
            name: ui.item.value
            latitude: ui.item.latitude
            longitude: ui.item.longitude
          #trigger a custom event if you want other artifacts to react 
          #upon autocompletion
          model.trigger('behavior:autocomplete.locality.done')

        source: (request, response) ->
          #straightforward implementation (mine actually uses a local cache 
          #that I stripped off)
          $.ajax
            url: 'http://api.whatever.com/search/destination'
            dataType:"json"
            data:request
            success: (data) ->
              response(data)

  #return an instanciated autocomplete to keep the cache alive
  return new LocalityAutocompleteBehavior()

使用此行为的视图摘录:

define [
  'jquery'

  #if you're using requirejs and handlebars you should check out
  #https://github.com/SlexAxton/require-handlebars-plugin
  'hbs!modules/search/templates/SearchActivityFormTemplate'

  #model dependencies
  'modules/search/models/SearchRequest'

  #autocomplete behavior for the locality field
  'modules/core/behaviors/LocalityAutocompleteBehavior'


  ], ($, FormTemplate, SearchRequest, LocalityAutocompleteBehavior ) ->
    #SearchFormView handles common stuff like searching upon 'enter' keyup, 
    #click on '.search', etc...
    class SearchActivityFormView extends SearchFormView

    template: FormTemplate

    #I like to keep refs to the jQuery object my views use often
    $term: undefined
    $locality: undefined

    initialize: ->
      @render()

    render: =>
      #render the search form
      @$el.html(@template())
      #initialize the refs to the inputs we'll use later on
      @$term = @$('input.term')
      @$locality = @$('input.locality')

      #Apply the locality autocomplete behavior to the form field 'locality'
      LocalityAutocompleteBehavior.apply(@model, @$locality)

      #return this view as a common practice to allow for chaining
      @

    search: =>
      #A search is just an update to the 'query' attribute of the SearchRequest 
      #model which will perform a 'fetch' on 'change:query', and I have a result 
      #view using using the same model that will render on 'change:results'... 
      #I love Backbone :-D
      @model.setQuery {term:  @$term.val(), locality: @$locality.val()}

答案 3 :(得分:1)

这是一篇有用的文章,给出了Backbone.js + jQuery中自动完成的示例,并将其与纯jQuery进行了比较 http://rockyj.in/2012/05/25/intro_to_backbone_jQuery.html