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

12

我正在学习Backbone.js。目前我认为,如果使用Backbone.js,则所有客户端JavaScript/jQuery都应该与Backbone集成。通过各种在线教程,我可以看到Backbone的工作方式并理解其基本原理。

但是jQuery UI小部件之类的东西呢?这些也应该与Backbone.js集成吗?例如,我想在表单字段上使用jQuery UI自动完成小部件(请参见下面的代码)。如何使用Backbone.js进行此操作(或者一个人是否不必为此使用Backbone)?这似乎Backbone“模型”和“集合”无法与jQuery自动完成小部件一起使用,因为这种东西已经包含在jQuery UI小部件本身中。

(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);
什么是标准惯例?我所能想到的唯一办法就是创建一个视图然后在渲染函数中添加小部件。但这对我来说并不像Backbone。
4个回答

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();
        }
    });

    ...
},  
...

记得使用 'reset' 事件! - miguelr
你介意加上其余的代码吗?这似乎是最好的解决方案,但我遇到了问题,不确定你所说的“使用重置事件”是什么意思。 - reach4thelasers

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

希望这可以帮上忙。

3

我正在使用自动完成来增强与不同模型和不同搜索API交互的许多表单视图中的“locality”字段。

在这种情况下,我觉得“自动完成位置”是字段的“行为”,而不是视图本身,为了保持DRY,我以这种方式实现:

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

以下是一些Coffeescript代码片段(我还使用requirejs和神奇的jquery-ui amd包装器:https://github.com/jrburke/jqueryui-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()}

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接