2014-10-11 143 views
0

下面的客戶端JavaScript不起作用,因爲代碼在cb被填充之前完成。在SignalR 中填充cb函數失敗,因爲調用是異步的,所以太晚了。如何使用Twitter Typeahead與SignalR獲取自動填充建議

我如何填充來源使用SignalR響應用戶輸入到我的typeahead文本框?

var tonameSource = function (query, cb) { 

     setTimeout(function() { 
      var prefix = $('#toname').val(); 
      var myCBval = []; 
      talk.server.getpcont(prefix, ConnectionId) 
        .done(function (mmID) { 
         $.each(mmID, function() { 
          var myOBJ = this; 
          myCBval.push({ 
           name: myOBJ.name, 
           ID: myOBJ.ID 
          }); 
         }); 
        }).fail(function (error) { 
         // 
        });    

      cb(myCBval); 

     }, 300) 
    }; 

    $(".tt-toname").typeahead(null, { 
     minLength: 2, 
     source: tonameSource, 
     displayKey: 'name', 
    }).on('typeahead:selected', function (obj, datum) { 
     //$(".tt-name").typeahead('val', datum.name).typeahead('close'); 
    }); 

回答

1

很高興我發現trigger the typeahead event programmatically using jquery這給了我類比的答案。因此SignalR可以填充Twitter Typeahead建議。

在我的情況下,答案是設置來源,如下所示。從那裏我瞭解到,調用回調函數只能在完成失敗內部完成,並且在對SignalR服務器的調用進行異步返回時運行。它是產生顯示建議的回調方法。

<div class="typeahead-wrapper"> 
     <input class="tt-toname" id="toname" name="toname" type="text" placeholder="Enter name" /> 
    </div> 

(推薦跳到下面的更新本節!)

$(".tt-toname").typeahead(null, { 
     minLength: 2,  

     // begin source  
     source: function (query, process) { 
      var prefix = $('#toname').val(); 
      var myCBval = [];// my callback value 

      // "talk" is = $.connection.talkHub; and set elsewhere globally 
      //getpcont is a custom SignalR method that is on the server 
      talk.server.getpcont(prefix, ConnectionId) 
        .done(function (mmID) { 
         $.each(mmID, function() { 
          var myOBJ = this; 
          myCBval.push({ 
           name: myOBJ.name, 
           ID: myOBJ.ID 
          }); 
          process(myCBval);//process is a callback method 
         }); 
        }).fail(function (error) { 
         process([]);//process is a callback method, don't know if this is necessary here, but will produce no suggestions 
        }); 
     } 
     // end source 

     , 
     displayKey: 'name', 
    }).on('typeahead:selected', function (obj, datum) { 
     //$(".tt-name").typeahead('val', datum.name).typeahead('close'); 
    }); 

已更新2015年9月11日與typeahead.js版本0.11.1工作----------- -------------

$(".tt-toname").typeahead({ 
     // hint: true, 
     //highlight: true, 
     minLength: 2   
    } 
     , 
     { 
      name: 'myname', 
      limit:10, 
      source: function (q, sync, async) { 

       talk.server.getcontacts(q, ConnectionId) 
         .done(function (data, status) 
         { 
          async(data); 
         } 
         ).fail(function (error) { 
          alert("in fail" + error); 
         }); 

      }, 
      displayKey: 'name' 
     }); 

另見:Bootstrap Typeahead not showing hints as expected

+0

這是偉大的,出色地完成 – 2014-11-19 13:03:09

相關問題