Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly add a jQuery UI autocomplete widget using Backbone.js

I am in the process of learning Backbone.js. I currently assume that if one is using Backbone.js then all client-side javascript/jQuery should be integrated with Backbone. From the various online tutorials I can see how Backbone works and understand its underlying principles.

But what about things like jQuery UI widgets? Should these also be integrated with Backbone.js? For example, I want to use the jQuery UI Autocomplete widget on a form field (See code below). How would I go about doing this with Backbone.js (or would one not bother using Backbone for such things)? It seems like Backbone 'Model' and 'Collection' wouldn't work with the jQuery Autocomplete Widget, since that kind of stuff is tied up within the jQuery UI Widget itself.

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

What is the standard practice for such things? The only thing I could think of was to create a view and then add the widget in the render function. But this doesn't really seem very Backbone-ish to me.

like image 366
Benjen Avatar asked Mar 12 '12 07:03

Benjen


People also ask

How does autocomplete work in jQuery?

In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time. The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.

How can create autocomplete search box in jQuery?

Syntax: $("TagId"). autocomplete({ source : itemList // List of Words. })

Which are jQuery ui widgets?

a jQuery UI widget is a specialized jQuery plug-in. Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in's lifetime.


2 Answers

In my view, the collection with the data is accessed using this.collection, like @saniko i set up the autocomplete in the view's render function:

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

    ...
},  
...
like image 121
miguelr Avatar answered Sep 28 '22 08:09

miguelr


Attache all your plugins when you render the view:

you can do something like this:

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

Hope that helps

like image 45
danikoren Avatar answered Sep 28 '22 09:09

danikoren