ExtJS Hack: Dynamic ComboBox & Remote On-Demand Loading With Local Filtering ExtJS Hack: dinâmica ComboBox & remoto On-Demand com carga local de filtragem
In ExtJS you can create ComboBox which loads data from the server. Em ExtJS você pode criar ComboBox que carrega os dados do servidor. You can also code so that new data is loaded from the server in response to an event like changing selection of another ComboBox. Você também pode código para que os novos dados são carregados a partir do servidor, em resposta a um evento como alterar selecção de outro ComboBox. However it also means that the filtering is done remotely which is slow. No entanto, também significa que a filtragem é feita remotamente, que é lento.
In ExtJS ComboBox automatic filtering is a nifty capability where the ComboBox items are automatically filtered to show only the values which matches the text you typed so far. Em ExtJS ComboBox filtragem automática é um bacana onde a capacidade ComboBox itens são automaticamente filtrada para mostrar apenas os valores que coincide com o texto que você digitou até agora. It can also auto-fill the rest for you. Também pode auto-preenchimento do resto para você. This powerful capability comes at a price for remote mode. Esta poderosa capacidade tem um preço de modo remoto. Every time the data is filtered by sending a query to the server which can be slower than local query. Cada vez que os dados são filtrados através do envio de uma consulta para o servidor que pode ser mais lento do que o local consulta.
In many use cases the full data is already on the client side, fetched during the initial loading of the ComboBox. Em muitos casos, o uso de dados completo já se encontra no lado cliente, coletados durante o carregamento inicial do ComboBox. Subsequent filtering can be easily done on the client side. Posteriormente filtragem pode ser feito facilmente com o lado cliente. Let’s see how we can solve it. Vamos ver como podemos resolvê-lo.
Update: I have also filed a Update: Eu também têm apresentado um defect Defeito in ExtJS forum to hopefully incorporate the functionality in the core with suggested solutions. ExtJS no fórum de espera incorporar a funcionalidade do núcleo com propostas de solução. The defect details has been provided at the end of this post. Os detalhes defeito tenha sido fornecida no final deste post.
The intuitive approach to this problem is to load the ComboBox on an event handler after setting the baseParams of the store with appropriate parameters. A abordagem intuitiva para este problema está a carregar o ComboBox em um evento manipulador após a fixação da baseParams da loja com parâmetros adequados. This works in remote mode but not in local mode. Isto funciona em modo remoto, mas não em modo local. Now you want to set the ComboBox to local mode because you want to implement local filtering, right? Agora você deseja definir o modo ComboBox ao local, porque você deseja implementar locais de filtragem, certo?
The solution is far from obvious. A solução está longe de ser óbvia. In local mode ComboBox clears the filters of the store which in turn replaces the data in the store with the stored, and obviously stale, snapshot. No local modo ComboBox apura os filtros da loja que, por sua vez, substitui os dados da loja com a armazenados, e obviamente obsoleto, instantâneo. To solve this you must call combo.store.updateSnapshot() after the combo.store.load() call. Para resolver isto, você deve ligar para combo.store.updateSnapshot () após a combo.store.load () call.
Now where can you get this function? Agora, quando você pode obter essa função? Oh yes… Ah sim…
Ext.data.Store.prototype.updateSnapshot = function() { this.snapshot = this.data; } Ext.data.Store.prototype.updateSnapshot = function () (this.snapshot = this.data;) The on demand loading is accomplished by keeping the data in local mode and then loading the store once (use a boolean to check) on beforequery event handler. O carregamento é realizado sob demanda, mantendo os dados em modo local e, depois, a loja carregando uma vez (para verificar a utilização de um boolean) sobre beforequery evento manipulador. You have to use updateSnapshot() function after the load as explained above. Você tem que usar updateSnapshot () após função da carga, como explicado anteriormente.
Use cases Use casos
Let’s first look at the use cases which I am sure many will agree with. Vamos primeiro olhar para o uso casos que estou certo que muitos irão concordar com ele.1. I want to load a ComboBox on demand. Eu quero carregar uma ComboBox na procura. I have very large number of columns in a grid, each of which has a ComboBox to help selecting a value. Tenho grande número de colunas de uma grade, cada um dos quais tem um ComboBox para ajudar a selecionar um valor. I don’t want to load all the data upfront as that slows down the initial loading. Não quero carregar todos os dados iniciais como que diminui a carga inicial. So I want to load the data when the ComBox drop-down is clicked. Então eu quero carregar os dados quando o ComBox drop-down é clicado. I can easily do that in remote mode but the downside is that the filtering functionality asks the server for filtering. Eu posso fazer isto facilmente em modo remoto, mas a desvantagem é que a filtragem funcionalidade solicita ao servidor de filtragem. The data I fetched is fixed and it is already on the client, so there is no justification for bothering the server. Os dados coletados I é fixa e que já está no cliente, por isso não há qualquer justificação para incomodar o servidor.
2. An alternative scenario is when you have a dynamically loaded ComBox. Um cenário alternativo é quando você tem uma ComBox carregados dinamicamente. You would still like to do local filtering, when the data has been fully loaded, for better performance. Ainda quiser fazer filtragem local, quando os dados tenham sido completamente carregado, para um melhor desempenho. This might be the one you can better associate with. Este poderia ser um dos melhores você pode associar.
Defect Defeito
My solution was to keep the ComboBox in local mode but load the store on first access. A minha solução foi a de manter a ComboBox em modo local, mas carregar o armazém em primeiro acesso. This works perfectly in remote mode for the dynamically loading case. Isso funciona perfeitamente em modo remoto para carregar dinâmicamente o caso. However it doesn’t work when the mode is local. No entanto ele não funciona quando o modo é local. In local mode the doQuery() calls clearFilter() which replaces the new data in the store with old stale snapshot data. No local modo a doQuery () solicita clearFilter () que substitui os novos dados na loja com o velho obsoleto instantâneo dados.What is needed is to replace the snapshot data in this case with the current data in the store after a successful reload. O que é necessário é o de substituir o instantâneo dados, neste caso com os dados actuais na loja depois de uma bem sucedida reload.
The real defect is that in this case clearFilter() shouldn’t replace the store with old snapshot when the store has been refreshed by a call to load. O verdadeiro defeito é que, neste caso clearFilter () não deve substituir a antiga loja do snapshot quando a loja foi atualizado por uma chamada a carga.
Solution Solução
My solution was to create a method for this in ComboBox: A minha solução foi criar um método para este ComboBox em:
Code: Código:Ext.data.Store.prototype.updateSnapshot = function() { this.snapshot = this.data }Ext.data.Store.prototype.updateSnapshot = function () (this.data = this.snapshot)And then call this method after loading the ComboBox. E então chamada este método depois de carregar o ComboBox.
The solution works but I am not fully happy as it isn’t elegant. A solução funciona, mas não estou plenamente satisfeito, uma vez que não é elegante. Looking forward to hear a better idea in solving this problem. Olhando para a frente para ouvir uma idéia melhor de resolver este problema.
Additional Thoughts Adicional Pensamentos
I think there should be a way for clearFilter() to recognize when new data has been loaded versus when filtered data has been loaded for the old data. Penso que deveria haver um caminho para clearFilter () para reconhecer quando novos dados foram carregados quando versus dados filtrados foi carregado para os dados antigos. Both cases uses load(). Ambos os casos utiliza carga ().
The solution could be a new configuration parameter to load() which clearFilter() looks for and processes, if available. A solução poderia ser uma nova configuração parâmetro para carregar () que clearFilter () olha para os processos e, se disponível.
Filed under Arquivado em Ajax , De Browser Navegador , De Headline News Headline News , De How To How To , De Javascript , De Programming Programação , De Tech Note Nota Tech , De Web , De Web 2.0 Web 2,0 | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | este artigo |
Email this Article E-mail este artigo
You may also like to read Você pode também gosta de ler |




October 25th, 2007 at 10:56 am Outubro 25o, 2007 em 10:56
Hello,when I call Ext.data.Store.prototype.updateSnapshot after loading the ComboBox ,the hack had solve. Olá, quando eu chamo Ext.data.Store.prototype.updateSnapshot depois de carregar o ComboBox, a cortar tinha resolver.
But I click the comboBoxA again, the comboBoxB not list the data for ever. Mas eu clicar no comboBoxA novamente, a não comboBoxB lista os dados de cada vez.
How u solve this problem? U Como resolver este problema?
March 7th, 2008 at 3:36 pm De 7 de março, 2008, 3:36 pm
I would like to see a full source of how you are accomplishing this, unfortunately just the one snippet for me is not enough to get going. Gostaria de ver uma fonte completa de como está a realizar isto, infelizmente, apenas a um trecho para mim não é suficiente para se deslocar. A complete sample would definitely help here. Uma amostra completa com certeza gostaria de ajudar aqui.