2012-03-12 61 views
12

我正在學習Backbone.js的過程。我目前假設,如果有人使用Backbone.js,那麼所有客戶端JavaScript/jQuery應與Backbone集成。從各種在線教程中,我可以看到Backbone如何工作並理解其基本原理。如何使用Backbone.js正確添加jQuery UI自動填充小部件

但是,像jQuery UI小部件呢?這些還應該與Backbone.js集成嗎?例如,我想在表單字段上使用jQuery UI Autocomplete小部件(請參閱下面的代碼)。我將如何去與Backbone.js做這件事(或者不會打擾使用骨幹這種事情)?看起來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); 

這種事情的標準做法是什麼?我能想到的唯一的事情就是創建一個視圖,然後在渲染函數中添加這個小部件。但是這對我來說並不是非常重要。

,你可以這樣做:當你渲染視圖

回答

3

武官所有插件

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

希望幫助

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

    ... 
}, 
... 
+0

請記住使用「reset''事件! – miguelr 2012-04-12 10:06:05

+0

你介意爲此添加其他代碼嗎?這似乎是最好的解決方案,但我有問題,我不確定你的意思是「使用重置事件」 – reach4thelasers 2012-04-19 13:00:52

3

我使用的是自動完成的,以加強與不同的互動形式,許多意見「局部性」領域比較它與純粹的jQuery模型和不同的搜索API。

在這種情況下,我覺得「自動完成地方」是該領域的「行爲」,而不是一個視圖本身並保持乾燥我實現這種方式:

  • 我有一個LocalityAutocompleteBehavior實例
  • 我必須通過應用行爲,表單字段,他們希望
  • 行爲結合「的jQuery UI的自動完成」窗體域,然後在自動完成發生創建視圖的模型的屬性,認爲使用該實例的意見然後可以在這些領域做任何想做的事情。

下面是一些CoffeeScript的提取物(我還使用requirejs和https://github.com/jrburke/jqueryui-amd的真棒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()} 
相關問題