I have a search bar that data binds results in a grid using afterkeydown. However, the binding is happening too quickly. Users only have time for a single key press before the results start to populate. I have a Block UI element that prevents interaction with the page while results are loading, thus stopping the search query at a single character until results are loaded.
I know there's a knockout extender called rateLimit to delay the call until after a specified time period after changes stop, but I've been unable to see any difference when add it to the definition of 'searchTerm'. Is there another method I should be using?
I have provided my search box, the definition of the 'searchTerm' observable and where it's used to load my grid results:
<input data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
Knockout:
var app = app || {};
app.data = #Html.Raw(Json.Encode(Model));
app.CreateVM = function (data) {
var vm = {};
vm.searchTerm = ko.observable(data.Search);
...
}
vm.filterResults = function () {
app.getResultsList(vm.selectedItem(), vm.searchTerm(), vm.currentPage() + 1, vm.sortDirection(), vm.sortProperty(), updateGrid);
}
app.getResultsList = function (Id, searchTerm, pageIndex, sortDirection, sortProperty, callBack) {
$.ajaxCall({
url: $('#clientGrid').data('url'),
type: 'GET',
dataType: 'json',
data: {
Id: Id,
pageIndex: pageIndex,
sortDirection: sortDirection,
sortProperty: sortProperty,
filter: searchTerm
},
...
}
You haven't posted the relevant code so I can't be sure, but I'm guessing the problem is that you're firing off updates manually every time rather than using the searchTerm observable's change events to trigger it. The knockout way to do this would be to data-bind your results grid to a computed observable.
Here's a jsFiddle demonstrating the rateLimit extension: fiddle
If you want to include some more code regarding what triggers your ajax call to update your grid we can probably help pinpoint the problem.
Related
I'm trying to add a new empty line in ui-grid. I've tried looking in different tuto and example, but all that I found didn't reply to my spec, and I wasn't able to adapt it to what I'm looking for.
In fact I'm looking how to add a new empty line in an existing ui-grid neither using a button outside the grid nor a button in the rowfooter.
I'm looking to add a abutton in the grid like the + button shown in the screen shot below
or may be render automatically a new empty line when the rendering the ui-grid and a new one when all rows were filled.
I tried doing that using function in cell template but it's not working.
any help is really appreciated
The first option sounds like more of a CSS issue to me. Essentially, the add button would use some sort of font library containing a +, and you would need to position it in the corner of the grid. Perhaps looking at the grid footer would be a starting place. It sounds like you've seen the basics of creating an add row button here: http://ui-grid.info/docs/#/tutorial/112_swapping_data
The second option (render automatically a new empty line when the rendering the ui-grid and a new one when all rows were filled) requires a JavaScript approach.
The basic logic I followed is:
(Assume) Some data loads from somewhere in a backend (in this sample, it's a simulated load returning a promise as $http or $resource would).
After that data is loaded, we append a new row. We wait for the data first; otherwise we'd not be pushing the new row to the correct location.
Upon completion of the edit action, we set a timeout to ensure subsequent edits on other cells do not keep firing a new row. If the timeout is reached, we append a new row. If a subsequent edit action occurs, and a timeout promise exists (for adding a new row), we cancel it. Once no edit actions occur, and the timeout is reached, we push the new row.
To ensure that we are only taking action when our "extra row" is modified, when we create a row, a reference is maintained to the current row such that we can evaluate whether or not a received event is of interest (var newRowTimeoutPromise).
The core logic in code is below, with a sample implementation in Plnkr:
var extraRow = null,
addNewTimeoutMillis = 2000,
newRowTimeoutPromise = null;
loadData().then(function(data) {
$scope.gridOpts.data = data;
}).finally(function() {
// add initial empty row, and set our reference to it
extraRow = addEmptyRow($scope.gridOpts.data);
})
$scope.gridOpts = {
showGridFooter: true,
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
// listen for cell edit completion
gridApi.edit.on.afterCellEdit($scope, function(rowEntity, colDef, newValue, oldValue) {
// test if the edited row was the "extra row"
// otherwise, and edit to any row would fire a new row
// Set a timeout so we don't create a new row if the user has
// not finished their edit(s) on other fields
newRowTimeoutPromise = $timeout(function() {
if (rowEntity == extraRow) {
// add a new empty row, and set our reference to it
extraRow = addEmptyRow($scope.gridOpts.data);
newRowTimeoutPromise = null;
}
}, addNewTimeoutMillis);
})
// Listen for cell edit start, and cancel if we have a pending new
// row add. Otherwise, each time you finish the edit on a cell,
// this will fire.
gridApi.edit.on.beginCellEdit($scope, function(rowEntity, colDef, newValue, oldValue) {
if (newRowTimeoutPromise != null) {
$timeout.cancel(newRowTimeoutPromise);
}
})
}
};
http://plnkr.co/edit/IMisQEHlaZDCmCSpmnMZ?p=preview
I used jQuery to fetch and change style of specific cell elements of the cell template.
Here is a helpful Fiddle
Here is the controller script : -
var app = angular.module('app', ['ngTouch', 'ui.grid']);
app.controller('MainCtrl', ['$scope',
function($scope) {
$scope.gridOptions = {};
$scope.Add = function() {
$scope.gridOptions.data.push( { firstName: ' ',lastName:'',company:'' });
$(".ui-grid-coluiGrid").prevObject["0"].activeElement.style.display="none";
$(".ui-grid-cell")[$scope.gridOptions.data.length-2].style.display="inline";
};
$scope.gridOptions.onRegisterApi = registerGridApi;
function registerGridApi(gridApi) {
$scope.gridApi= gridApi
};
$scope.gridOptions.columnDefs = [{
name: 'firstName',
field: 'firstName',
}, {
name: 'lastNamer',
field: 'firstName'
}, {
name: 'ShowScope',
cellTemplate: '<button id="btb" ng-click="grid.appScope.Add()">+</button>'
}];
$scope.gridOptions.data = [{ yourdata}];
}
]);
To make it work properly 2 more things have to be done
Use cellContentEditable to make the rows editable
In order to disable display style of cell template button that appears on cells corresponding to rows of already existing data,you could use angular foreach or a for loop to iterate through these rows and disable style(I tried using renderContainers but it always returns the length of rendered rows outside Add functions as 0).
I have a working plunker over here.
http://plnkr.co/edit/Vnn4K5DcCdiercc22Vry?p=preview
In columnDefs, I have defined a separate column for add:
{
name: 'add',
displayName: '',
enableCellEdit: false,
enableColumnMenu: false,
width: '3%',
cellTemplate: '<div class="ui-grid-cell-contents" ng-click="grid.appScope.addRow()"><span ng-click="grid.appScope.addRow()">Add</span></div>'
}
And
$scope.addRow= function(){
var newlist = {"remarks":'',"testName":''};
$scope.gridOptions.data.push(newlist);
}
Update: A second plunker with bootstrap icons for add/remove
http://plnkr.co/edit/FjsA2r?p=preview
I am trying to implement a feature to select an item in kendo's multi-select control with server filtering. when user presses tab on the selected item. Here is my code of kepdown event:
if (e.keyCode === 9) {
var selectedItem = multiSelect.current();
if (selectedItem) {
var selectedIndex = selectedItem.data("idx");
if (selectedIndex >= 0) {
var currentValue = multiSelect.value().slice();
var dataitems = multiSelect.dataSource.view();
var selectedDataItem = dataitems[selectedIndex];
multiSelect.dataSource.filter({});
currentValue.push(selectedDataItem.relatedId);
multiSelect.value(currentValue);
multiSelect.trigger("change");
}
}
}
But it works fine as long as I am searching in same data view i.e. lets say I select two values starting with Cloud and then I select a value starting with App then kendo will remove previous two values starting with Cloud and control will contain just one value selected at the last.
I debugged kendo's code that the issue in function _index of kendo because it finds value in dataSource.view
I have recreated the issue at http://dojo.telerik.com/OtAvi
Your code is not working because you have serverFiltering set to true in the dataSource:
dataSource: {
type: "odata",
serverFiltering: true,
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products",
}
}
},
Since the data is being filtered on the server, the call multiSelect.dataSource.filter({}); is only clearing the already filtered data. With that said, when you call multiSelect.value(currentValue);, only the values from the currently filtered dataSource can be selected. This is causing the selection to only hold items from the current dataView.
Unless you have a strong reason not to, your easiest fix is to set serverFiltering set to false.
I'm writing a directive wrapper around a typeahead input. This directive listens for changes on a link and get's new data + options for the typeahead.
I can simply simulate this behaviour with a $timeout and demonstrated it in this plnkr.co.
JS
app.controller('sample', function($scope, $timeout) {
$scope.options = ['1800', '1900', '2100'];
// Simulate some latency
$timeout(function () {
$scope.options.push('1850');
}, 4000);
});
HTML
<div>
<input type="text" ng-model="optionValue" typeahead="opt for opt in options | filter:$viewValue">
</div>
If you start typing '18' in the input field it shows 1800 as expected. But when 1850 get's added after an amount of time, the selectable options from typeahead are not being updated.
-- FYI my real live directive looks like this --
$scope.$watch($interpolate(url), function (newUrl) {
$http.get(newUrl).then(function (response) {
$scope.options = response;
});
});
I tried to use typeahead="opt for opt in getData()" but this doesn't work because the interpolated value is not yet up to date. It's always one value behind.
Seems like an issue to post on AngularUI Bootstrap website. Matches are getting selected on every keystroke but they don't get updated if you change the underlying data between keystrokes. I don't see any work-around for this, except maybe triggering the appropriate key event handler on the input manually (when you change the collection).
If someone interested in the solution, here is how I solved it at the moment. I'm not happy with the end result, please provide me some feedback :-).
Plunkr
Check out updated-bootstrap.js, I had to add the following in order to make it work:
A custom attribute that'll be use for the $watchCollection
var customOptions = attrs.typeaheadCustomOptions || '';
In the function where it gets the matches I've added a watch if customOptions is provided:
if (customOptions) {
originalScope.$watchCollection(customOptions, function (matches) {
resetMatches();
updateMatches(matches);
});
}
And that was basically it :-), the updateMatches is just an abstraction of existing code. It's not being used by me and the manual update.
var updateMatches = function(matches) {
for (var i = 0; i < matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = modelCtrl.$viewValue;
};
Opened issue on github
I'm loading options into an HTML5 datalist element dynamically. However, the browser attempts to show the datalist before the options have loaded. This results in the list not being shown or sometimes a partial list being shown. Is there any way to refresh the list via JavaScript once the options have loaded?
HTML
<input type="text" id="ingredient" list="ingredients">
<datalist id="ingredients"></datalist>
JavaScript
$("#ingredient").on("keyup", function(event) {
var value = $(this).val();
$.ajax({
url: "/api/ingredients",
data: {search: value.length > 0 ? value + "*" : ""},
success: function(ingredients) {
$("#ingredients").empty();
for (var i in ingredients) {
$("<option/>").html(ingredients[i].name).appendTo("#ingredients");
}
// Trigger a refresh of the rendered datalist
}
});
});
Note: In Chrome and Opera, the entire list is only shown if the user clicks on the input after entering text. However, I'd like the entire list to appear as the user types. Firefox is not a problem, as it appears to refresh the list automatically when the options are updated.
UPDATE
I'm not sure this question has a satisfactory answer, as I believe this is simply a shortcoming of certain browsers. If a datalist is updated, the browser should refresh the list, but some browsers (including Chrome and Opera) simply do not do this. Hacks?
Quite a long time after question but I found a workaround for IE and Chrome (not tested on Opera and already OK for Firefox).
The solution is to focus the input at the end of success (or done) function like this :
$("#ingredient").on("keyup", function(event) {
var _this = $(this);
var value = _this.val();
$.ajax({
url: "/api/ingredients",
data: { search: value.length > 0 ? value + "*" : "" },
success: function(ingredients) {
$("#ingredients").empty();
for (var i in ingredients) {
$("<option/>").html(ingredients[i].name).appendTo("#ingredients");
}
// Trigger a refresh of the rendered datalist
// Workaround using focus()
_this.focus();
}
});
It works on Firefox, Chrome and IE 11+ (perhaps 10).
I had the same problem when updating datalist.
The new values would not show until new input event.
I tried every suggested solutions but nothing using Firefox and
updating datalist via AJAX.
However, I solved the problem (for simplicity, I'll use your example):
<input type="text" id="ingredient" list="ingredients" **autocomplete="off"**>
<datalist id="ingredients"></datalist>
$("#ingredient").on("**input**", function(event) { ....}
Autocomplete and input is the couple that solve my problems and it works with Chrome too.
You can probably eliminate the problem if you don't make AJAX request on every key stroke. You can try throttle technique using set/cleatTimeout to issue request after 500ms after the last char typed:
$("#ingredient").on("keyup", function(event) {
clearTimeout($(this).data('timeout'));
$(this).data('timeout', setTimeout($.proxy(function() {
var value = $(this).val();
$.ajax({
url: "/api/ingredients",
data: {search: value.length > 0 ? value + "*" : ""},
success: function(ingredients) {
$("#ingredients").empty();
for (var i = 0; i < ingredients.length; i++) {
$("<option/>").html(ingredients[i].name).appendTo("#ingredients");
}
}
});
}, this), 500));
});
Yoyo gave the correct solution, but here's a better way to structure your inserts into the DOM.
$("#ingredient").on("keyup", function(event) {
var _this = $(this);
var value = _this.val();
$.ajax({
url: "/api/ingredients",
data: { search: value.length > 0 ? value + "*" : "" },
success: function(ingredients) {
var options = ingredients.map(function(ingredient) {
var option = document.createElement('option');
option.value = ingredient.name;
return option;
});
$("#ingredients")
.empty()
.append(options);
// Trigger a refresh of the rendered datalist
// Workaround using focus()
_this.focus();
}
});
Less DOM manipulation
With this refinement, I'm only inserting into the DOM a single time per each successful callback. This cuts down on the browser needing to re-render, and will help improve any "blips" in the view.
Functional Programming and Less Idiomatic jQuery
Here we are using the Array.prototype.map to clean up some of the jQuery and make things a bit less idiomatic. You can see from the ECMA Chart that this function will work in all browsers you are targeting.
Not Hacky
This by no means is hacky. IE appears to be the only browser that doesn't automatically refresh the input to display the new list options. focus() is just a way to ensure the input is refocused which forces a refresh of the view.
This solution works very well in all of the browsers that my company has to support internally, IE10+ Chrome and Firefox.
Place your #ingredients element is inside #container and try this code:
$.ajax({
url: "/api/ingredients",
data: {search: value.length > 0 ? value + "*" : ""},
success: function(ingredients) {
$("#ingredients").remove();
var item = $('<datalist id="ingredients"></datalist>');
for (var i in ingredients) {
item.append("<option>"+ ingredients[i].name +"</option>");
}
item.appendTo('#container');
}
});
even better without #container and using jQuery replaceWith():
$.ajax({
url: "/api/ingredients",
data: {search: value.length > 0 ? value + "*" : ""},
success: function(ingredients) {
var item = $('<datalist id="ingredients"></datalist>');
for (var i in ingredients) {
item.append("<option>"+ ingredients[i].name +"</option>");
}
$("#ingredients").replaceWith(item);
}
});
Your issue is that the AJAX is asynchronous.
You'd actually have to have a callback for the AJAX which you call onSuccess which would then update the datalist. Of course, then you might not have great performance/still have a "skipping" behavior, where your datalist options are lagging behind.
If your list of items from the AJAX isn't too large, you should:
1. load the ENTIRE list into memory array with the first query, then...
1. use a filtering function that is applied to the array each time you have a keyUp event.
I found a solution tested only on GNOME Web (WebKit) that consist on set the 'list' attribute of the input element to empty string and, inmediately after, set it again with the id of the datalist element. Here is the example, supose that your input element is stored in a variable named input_element:
var datalist = document.getElementById(input_element.list.id);
// at this point input_element.list.id is equals to datalist.id
// ... update datalist element here
// And now the trick:
input_element.setAttribute('list','')
input_element.setAttribute('list',datalist.id)
I'm new to the whole Backbone (and I'm actually not much of a JavaScript programmer yet), and I'm running into issues with a filter form.
Basically I have a database that my backbone collection gets populated from. On the page, there is a filter section where I can checkmark things such as: "Jobstatus: Running, Completed, Failed, etc..." Or input such as "User name: test0." All that works great until I started paginating my results.
I have a router set up to handle #page/:page. This works as well, say I go to page 2 with no filters checked, and then on page 2 I check some filters (which right now sets my results back to page 1 by using navigate(page/1)), when I hit my back button, I go back to page 2 (since that is where my no filter results were last on), but my filter box is still checked.
So if there are 10 rows per page and I have 14 results with no filters. I go to page 2 to see results 11-14, check a filter that returns me to page 1 with a total of 5 results, and then i hit back. I am now on page 2 of those filtered results seeing rows 11-5 of 5...
Is there anyway for the history to remember the form checkboxes and other inputs? So if I hit back in the situation I describe, it goes to page 2, but with the form filters removes as they were prior.
I was thinking I'd have to use routes for every value on the form... but hoping there is a better way of doing this (hopefully without rewriting the entire code as well).
Any help is appreciated.
I have two main views for input: one tied to the filter form, one for the pagination selection. The filter form view calls another view for the results (which is ties to a collection of rows).
Here is the filter form view:
var FilterForm = Backbone.View.extend({
events: {
"submit": "refreshData",
"change input": "refreshData"
},
initialize: function () {
this.refreshData();
},
refreshData: function () {
Backbone.history.navigate('page/1');
pageNumberModel.set('pageNumber', 1);
this.newPage();
},
newPage: function () {
var pageNumber = pageNumberModel.get('pageNumber');
var rowsPerPage = pageNumberModel.get('rowsPerPage');
var startRow = ((pageNumber * rowsPerPage) - rowsPerPage) + 1;
var endRow = startRow + (rowsPerPage - 1);
$('#startrow').val(startRow);
$('#endrow').val(endRow);
var inputData = this.$el.serializeArray();
var inputDatareduced = _(inputData).reduce(function (acc, field) {
acc[field.name] = field.value;
return acc;
});
$.get("Database.aspx", inputData, function (outputData) {
jobQueueRows.set($.parseJSON($.parseJSON(outputData)['JobQueue']));
jobQueueRowsView.render();
pageNumberModel.set($.parseJSON($.parseJSON(outputData)['Pagination']));
pageNumberView.render();
rowNumberView.render();
});
}
});
I would recommend creating a filterModel for your FilterForm view and using that to hold the state. Here is a reference implementation.
FilterModel:
var FilterModel = Backbone.Model.extend({
initialize: function(){
if( !this.get('filters'))
this.set({filters: new Array()});
},
applyFilter: function(key){
var filters = this.get("filters");
set("filters", _.union(filters, key));
return this;
},
removeFilter: function(key){
var filters = this.get("filters");
set("filters", _.without(filters, key));
return this;
},
defaults: {
fooFilters: [
{key: "size", label: "Filter By Size"},
{key: "color", label: "Past Week"}]
}
});
Bind a handler in your view to update the filter model:
filterClicked: function (e) {
var filter = $(e.target);
if(filter.is(':checked'))
this.model.applyFilter(filter.attr("id"));
else
this.model.removeFilter(filter.attr("id"));
},
Modify your filter template to apply the models state to your checkboxes when rendering:
<ul id="fooFilters" class="foo-filter-list">
<% _.each(fooFilters, function(f) { %>
<li>
<label for="<%=f.key%>"><%=f.name%></label>
<input type="checkbox" name="" value="" id="<%=f.key%>" <%if($.inArray(f.key, filters) === -1 {%>checked<%}%>/>
</li>
<% }); %>
</ul>