8

我正在使用typeahead/bloodhound使用自舉-tokenfield。帶有先頭/血獵的自舉Tokenfield排除令牌

我可以防止相同的令牌在令牌字段中使用兩次,但同樣的令牌仍然出現在先行迴應中。我如何排除已經在令牌字段中的令牌?

var engine = new Bloodhound({ 
    remote: { 
    url: API_URL + '?action=message_friends&q=%QUERY', 
    filter: function (response) { 
     return $.map(response.users, function (user) { 
     return { 
      value: user.user_id, 
      label: user.name 
     }; 
     }); 
    } 
    }, 
    datumTokenizer: function(d) { 
    return Bloodhound.tokenizers.whitespace(d.value); 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace  
); 

engine.initialize(); 

$('#to-tags').tokenfield({ 
    typeahead: [ 
    { 
     hint: false 
    }, 
    { 
     name: 'users', 
     displayKey: 'label', 
     source: engine.ttAdapter() 
    } 
    ] 
}).on('tokenfield:createtoken', function (event) { 
    var existingTokens = $(this).tokenfield('getTokens'); 
    $.each(existingTokens, function(index, token) { 
    if (token.value === event.attrs.value) { 
     event.preventDefault(); 
    } 
    }); 
}); 

回答

7

更新濾波器功能已刪除用戶在令牌字段:

var engine = new Bloodhound({ 
     remote: { 
      url: API_URL + '?action=message_friends&q=%QUERY', 
      filter: function (response) { 
       var tagged_user = $('#to-tags').tokenfield('getTokens'); 
       return $.map(response.users, function (user) { 
        var exists = false; 
        for (i=0; i < tagged_user.length; i++) { 
         if (user.user_id == tagged_user[i].value) { 
          var exists = true; 
         } 
        } 
        if (!exists) { 
         return { 
          value: user.user_id, 
          label: user.name 
         }; 
        } 
       }); 
      } 
     }, 
     datumTokenizer: function (d) { 
      return Bloodhound.tokenizers.whitespace(d.value); 
     }, 
     queryTokenizer: Bloodhound.tokenizers.whitespace 
    }); 

    engine.initialize(); 

    $('#to-tags').tokenfield({ 
     delimiter: false, 
     typeahead: [ 
      { 
       hint: false 
      }, 
      { 
       name: 'users', 
       displayKey: 'label', 
       source: engine.ttAdapter() 
      } 
     ] 
    }) 
    .on('tokenfield:createtoken', function (e) { 
     var existingTokens = $(this).tokenfield('getTokens'); 
     if (existingTokens.length) { 
      $.each(existingTokens, function(index, token) { 
       if (token.value === e.attrs.value) { 
        e.preventDefault(); 
       } 
      }); 
     } 
    }); 
+0

當我使用此代碼的URL: '?動作= message_friends&Q =%QUERY' API_URL +,並檢查它作爲部分發布的標題中,帖子變量值是%Query,而不是實際值。什麼可能是錯的? –