2012-10-23 70 views
0

我從一個要點中拿出了這段代碼的基礎。當我第一次fetch()編輯集合,然後在render()調用tw-bootstap的.typeahead()它最初工作完美。Backbone.js和Bootstrap Typeahead - 異步獲取之後的渲染

但是,我已輸入keypress事件來嘗試限制由fetch()返回的數據大小。收集數據將返回並通過prepData()過濾,併到達render()。然而,在該階段,預先打印不工作。這可能是骨幹事件在這一點上壓倒了渲染?

// typeahead on the numbers 
var Bootstrap = {}; 

Bootstrap.Typeahead = Backbone.View.extend({ 
    el: '#autocompleteN', 
    tagName: 'input', 
    attributes: {"data-provide": "typeahead"}, 
    initialize: function(options){ 
     if(!this.collection) { 
      return null; 
     } 

     //this.collection.on("reset", this.prepData, this); 
    }, 
    events: { 
     "keypress": "setSearch" 
    }, 

    setSearch: _.throttle(function(e) { 
     var that=this; 
     var d = e.currentTarget.value; 

     // strip spaces and remove non-numerics 
     d = d.replace(/ /g,''); 
     d = d.replace(/[^0-9]/g, ''); 

     // if it's longer than 2, call a fetch; 
     if(d.length > 2) { 
      $.when(app.searchNums.fetch({url: 'api/index.php/search/num/'+d})).then(function() { 
       //console.dir("success"); 
       that.prepData(); 
      }); 
     } 

    }, 1000), 
    prepData: function() { 
     //console.dir("prepData called"); 
     var prepare = _.pluck(this.collection.models, 'attributes'); 
     this.property = this.options.property || _.keys(prepare[0])[0]; 

     this.items = this.options.items; 
     this.data = _.pluck(prepare, this.property); 

     this.render(); 
    }, 
    render: function() { 
     var that = this; 
     that.$el.typeahead({ 
      source: that.data, 
      //source: ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'], 
      items: that.items, 
      onselect: function(data) { 
       // render the results view here 
      } 
     }); 

     return this; 
    } 
}); 

var bui = new Bootstrap.Typeahead({ 
    collection: app.searchNums, 
    items: 5 
}); 

回答

0

你爲什麼不只是設置minLength的預輸入,這看起來是什麼你想幹什麼?