2012-03-12 58 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()} 
相关问题