2012-03-12 3 views
12

Backbone.js를 학습 중입니다. 나는 현재 Backbone.js를 사용하고 있다면 모든 클라이언트 측 javascript/jQuery가 Backbone과 통합되어야한다고 가정합니다. 다양한 온라인 자습서에서 Backbone이 어떻게 작동하고 기본 원칙을 이해하는지 확인할 수 있습니다.Backbone.js를 사용하여 jQuery UI 자동 완성 위젯을 올바르게 추가하는 방법

jQuery UI 위젯과 같은 것들은 어떻습니까? 이것도 Backbone.js와 통합해야합니까? 예를 들어, jQuery UI Autocomplete 위젯을 양식 필드에 사용하고 싶습니다 (아래 코드 참조). Backbone.js를 사용하여이 작업을 수행하려면 어떻게해야합니까? (또는 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); 

그런 것들에 대한 표준 관행은 무엇입니까? 내가 생각할 수있는 유일한 방법은 뷰를 작성한 다음 렌더 함수에 위젯을 추가하는 것입니다. 그러나 이것은 정말로 나에게 매우 백본처럼 보이지 않습니다.

는이 같은 수행 할 수 있습니다 : 당신이 뷰 렌더링

답변

3

무관의 모든 플러그인 내보기에서

7

을하는 데 도움이

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

희망을 데이터로 컬렉션에 액세스 @ saaniko와 같은 this.collection을 사용하여보기의 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

+0

나머지 코드를 추가 하시겠습니까?가장 좋은 솔루션 인 것 같지만 문제가 있으며 "리셋 이벤트 사용"이란 무엇인지 확실하지 않습니다. – reach4thelasers

3

내가 다른와 상호 작용하는 여러 형태의 뷰에서 "지역"필드를 강화하기 위해 자동 완성 기능을 사용하고 순수 jQuery를과 비교 유용한 기사입니다 모델 및 다른 검색 api.

  • 나는 LocalityAutocompleteBehavior의 인스턴스가이 경우에

    나는 "자동 완성 지역은"분야의 "행동"오히려 뷰 자체 내가 이런 식으로 구현 DRY을 유지하는 것보다,이라고 생각
  • 내가 원하는 양식 필드에 동작을 적용하여이 인스턴스를 사용하여보기가 있습니다.
  • "jquery-ui 자동 완성"을 양식 필드에 바인드 한 다음 자동 완성이 발생하면보기의 모델에 속성을 만듭니다.보기 이 분야에서 원하는대로 할 수 있습니다.

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

    그리고 뷰의 추출물 사용 : 여기

LocalityAutocompleteBehavior (나는 또한 requirejs 및 https://github.com/jrburke/jqueryui-amd에서 멋진 JQuery와 - UI AMD의 래퍼를 사용하고 있습니다) 일부 커피 스크립트 추출물이다 이 동작은

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