Efficient way to bind once but allowing to refresh the whole items - javascript

Let's suppose a list of 1000 items displayed with infinite scrolling.
Each item displays: a person's firstName, lastName, and mood. (to make it simple)
Initially, I didn't want to listen for updates.
So the great angular-bindonce directive or even better: angular 1.3 one-binding feature made the trick.
Now, I created a pull-to-refresh component, allowing to refresh the whole items.
However, as binding once, (and not reloading the page) my whole list didn't take the updates in account.
Using angular-bindonce, I have this currently:
<div bindonce ng-repeat="person in persons track by person.id">
<span bo-text="person.firstName"></span>
<span bo-text="person.lastName"></span>
<span bo-text="person.currentMood"></span>
</div>
The pull-to-refresh triggers this function:
$scope.refresh() {
Persons.getList(function(response)) {
$scope.persons = response.data; //data being an array
}
}
Question is:
Is there a way to refresh all the data ONLY when the pull-to-refresh is triggered?
In this case, I would be able to keep this one-binding that would greatly improve performance when dealing with huge lists of persons.
Until now, I'm forced to....use two-way binding, the natural way of Angular works.
More generally, how to deal with huge lists with infinite scrolling that needs to be updated only when some events are triggered?

Get angular-bind-notifier.
Use native bindings (with a somewhat modified syntax) and setup your markup like so:
<div ng-repeat="person in persons track by person.id" bind-notifier="{ eventKey:watchedExpression }">
<span>{{:eventKey:person.firstName}}</span>
<span>{{:eventKey:person.lastName}}</span>
<!-- or with ng-bind if you prefer that -->
<span ng-bind=":eventKey:person.currentMood"></span>
</div>
Now, whenever the value of watchedExpression changes - a $broadcast will be sent down through the childscope created by bind-notifier and tell every binding with the :key:expr syntax to re-evaluate.
If you need to, you can also send the $broadcast manually in the following format:
$scope.$broadcast('$$rebind::' + key) // where 'key' === 'eventKey' in the example above.

refresh-on directive could do the trick, found a reference HERE:
<div bindonce="persons" refresh-on="'refresh'" ng-repeat="person in persons track by person.id">
<span bo-text="person.firstName"></span>
<span bo-text="person.lastName"></span>
<span bo-text="person.currentMood"></span>
</div>

Instead of trying to work around not using two-way binding but still have all of its benefits there is more likely and easier solution. You say that there are 1,000 rows, are all 1,000 rows with the viewport / visible to the user at once?
I would assume not, so I would suggest using a buffered view for the list of items. Buffering the rows would mean that the rows that are not visible have no bindings but still take up space in the DOM so the scroll bar is always accurate.
The one major caveat of buffering is that all rows should be the same height, no variable height rows.
Here are some virtual scrolling / buffering directives to take a look at:
https://github.com/EnzeyNet/VirtualScroll
https://github.com/stackfull/angular-virtual-scroll
https://github.com/kamilkp/angular-vs-repeat

Related

What is "track by" in AngularJS and how does it work?

I don't really understand how track by works and what it does.
My main goal is to use it with ng-repeat to add some precision.
Using track by to track strings & duplicate values
Normally ng-repeat tracks each item by the item itself. For the given array objs = [ 'one', 'one', 2, 'five', 'string', 'foo'], ng-repeat attempts to track changes by each obj in the ng-repeat="obj in objs". The problem is that we have duplicate values and angular will throw an error. One way to solve that is to have angular track the objects by other means. For strings, track by $index is a good solution as you really haven't other means to track a string.
track by & triggering a digest & input focuses
You allude to the fact you're somewhat new to angular. A digest cycle occurs when angular performs an exhaustive check of each watched property in order to reflect any change to the correspodant view; often during a digest cycle it happens that your code modify other watched properties so the procedure needs to be performed again until angular detects no more changes.
For example: You click a button to update a model via ng-click, then you do somethings (i mean, the things you wrote in the callback to perform when an user makes a click), then angular trigger digest cycle in order to refresh the view. I'm not too articulate in explaining that so you should investigate further if that didn't clarify things.
So back to track by. Let's use an example:
call a service to return an array of objects
update an object within the array and save object
after save service, depending on what the API returns, you may:
replace the whole object OR
update a value on the existing object
reflect change in ng-repeat UI
How you track this object will determine how the UI reflects the change.
One of the most annoying UXs I've experienced is this. Say you have a table of objects, each cell has an input where you want to in-line edit those objects' properties. I want to change the value, then on-blur, save that object while moving to the next cell to edit while you might be waiting on the response. So this is an autosave type thing. Depending on how you setup your track by statement, you may lose current focus (e.g. the field you're currently editing) when the response gets written back into your array of objects.
When you add track by you basically tell angular to generate a single DOM element per data object in the given collection.
You can track by $index if your data source has duplicate identifiers.
If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.
Example:
[{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
Try to use the duplicate values in ng-repeat, you will get an error such as:
Error: ngRepeat:dupes Duplicate Key in Repeater
To avoid this kind of problems you should use track by $index. For example:
<ul>
<li ng-repeat="item in [1, 2, 3, 3] track by $index">
{{ item }}
</li>
</ul>
Here is how you would get $index in nested ng-repeat:
<div ng-repeat="row in matrix">
<div ng-repeat="column in row">
<span>outer: {{$parent.$index}} inner: {{$index}}</span>
</div>
</div>
Here are some resources that may help you:
track by $index documentation
ngRepeat documentation
2014 codelord.net article about ng-repeat performance and track by
You should use track by only if you need to go against the default behaviour of ng-repeat which is to remove duplicate items.
You can track the items using the scope property $index or specifying a custom function.
For instance:
<div ng-repeat="x in [42, 42, 43, 43] track by $index">
{{x}}
</div>
Display all values of the array (42 is displayed twice).
For reference: https://docs.angularjs.org/api/ng/directive/ngRepeat
Let's say, we have the following list:
<ul>
<li ng-repeat="item in items">
{{ item }}
</li>
</ul>
where, an item has the following structure:
{ 'id'=>id, 'name'=>name, 'description'=>description }
There is no problem whatsoever in this list until we wish to update it. For our own convenience we replace the list of items, with another updated list of items, as such:
items = newItems;
However, in this new list, few items change. Most items remain the same. Unfortunately Angular does not know how to identify our items and map them to the respective <li> elements, so it just deletes all elements and creates them again. This is extremely performance-costly in some cases and here is where track by comes in use.
By adding the track by clause to the element
<li ng-repeat="item in items track by item.id">
we are informing Angular, that the unique identifier of our items is item.id. Now Angular knows not to recreate all items, but only items with new ids, and only updates the rest. The performance improvement is significant in most cases. Also, personally, I like that I can monitor my items easier on my browser's developer tools, because they don't disappear every time I update them.

Dragula Angular2 update values using observable

I am writing a tree control using Angular2 and ng2-dragula (based on dragula). I am currently using something very similar to the example nested repeat example here. I have no problem loading in my list and getting drag and drop to work as expected. What I need to do is click a button, go back to the http service get fresh data, then update data on page. I know that I can use javascript to find the id and update that way but it doesn't seem like the correcy way to handle it.
Here is my component code - All this does is just over write the view data and completey undo any drags changed etc (im sure that is by design). I have tried a bunch of different different ways to use dragulaModel, but no matter what the whole component is re-rendered no matter what happens. I need to be able just to update the child text
I'm new to angular and want to make sure i follow the correct patterns
item.component.ts
loadItems(){
this._itemsService.getIems();
}
reloadIems(){
this._itemsService.getItems();
}
item.component.html
<div *ngIf="items">
<div class="holder">
<div *ngFor="let item of items | async">
<div (click)="checkCollapsed(item.text)" >
<div *ngIf='item.children' [dragula]='"first-bag"'>
<div *ngFor='let child of item.children' class="item">
<span class="handle">+</span><span id='{{child.id}}' [innerHtml]="child.text"> </span>
</div>
</div>
</div>
</div>
</div>
</div>
Edit
If I add a .subscribe to loadItems() then update this.items manually like this.items[0].children[0].text = "1000" in reloadItems() it works as i would like. Should I be manually updating the whole object this way? Seems like a hack
**Edit 2 **
I managed to get it to work by subscribing in the loadItems() then comparing the 2 objects in reloadItems, then making any necessary changes there. I think due to the subscribe it is autoupdating. Can anyone confirm if im doing it wrong/right (working plnkr here, leaving out the angular dependencies)

Transitioning between models on a ng-repeat

I'm building a directive (Angular 1.2) that will toggle between displaying two different lists - think of them as a list of "trending" items on the site and a list of items the user is "following". So we have a toggle that allows the user to choose which list is being displayed, with an ng-repeat below it showing the items.
There will be a good deal of overlap between these lists, and when the user toggles from one list to the other, I'd like items that are contained in both to transition from their places on the "outgoing" list to their places on the new one, rather than disappearing and reappearing.
My question isn't about how to achieve the actual animations (we're using ngAnimate), but about how I should structure the controller/data to. I'm thinking about my directive controller having a trendingList and a followingList (that contain the actual data items), and an activeList that points to whichever of the two are currently being displayed. So the ng-repeat is actually on activeList, and toggling is essentially:
$scope.toggleMode = function(){
if ($scope.mode == 'trending')
$scope.mode = following;
$scope.activeList = followingList;
else {/*the inverse...*/}
}
Is that the most reasonable approach? If so, how do I ensure that angular recognizes the equality of objects present in both lists?
Or is there an easier/cleaner way to do this?
From what I understand, angular isn't tracking the equality of objects in the list it is repeating. The animations are triggered when the DOM is manipulated, not when the data changes (though data changes will change the DOM). As to what you should do, I don't have experience with this problem so hopefully somebody can point you in the right direction!

Bootstrap ui angularjs with filter issue

I am using Bootstrap UI in my angular application. I have a tooltip in the html page which works fine. I noticed that after the tooltip is displayed and I move my mouse out, the Ui-bootstrap-tpls.js fires a method called "hideTooltipBind" which in turn calls $apply and it triggers the filters in that scope to reload.
Lets say I have 10 filters in the scope which is filtering an array of 100 each. Everytime a tooltip is displayed, all my filters are forced to reload again. How can I avoid this?
I am using
//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js
jquery-2.0.3.js
ui-bootstrap-tpls-0.11.0.js
I have attached the screenshot of the Call Stack
You can utilise some form of one-time binding. There are multiple options out there:
bind-once by pasvaz
angular-once by tadeuszwojcik
watch-fighters by abourget
fast-bind by me (fork off of Karl Seamons work)
There are some differences to the four (unrelated to your question at hand however):
bind-once is the most popular one seeing the most active development. Requires two directives to do the job (bindonce and bo-*).
angular-once is the minimalist of the four (don't quote me on that).
watch-fighters doesn't handle promise based data.
fast-bind has a notifier system for semi-static bindings, using the event bus in Angular.
Assuming you'd start leveraging either one of them, your bindings could look something like this:
<div bindonce="someData">
<span bo-bind="someData.text | yourFilter"></span>
</div>
<span once-text="someData.text | yourFilter"></span>
<span set-text="someData.text | yourFilter"></span>
<span bind-once="someData.text | yourFilter"></span>
This way, your filters would not reevaluate on Angular calls to $digest. If you are filtering a collection in your view (<li ng-repeat="coll | filter"></div>), I'd suggest you move those filters to the controller to reduce the amount of calls to the filters themselves.

Knockoutjs ObservableArray Keeps Doubling in Size

I am trying to understand some slightly odd behavior I am seeing in a page I am making using KnockoutJS. An observable array seems to get duplicate items every time I clear and reapply bindings. The quickest way to understand the problem is to look at this JSFiddle demo. Just click any edit button several times, and watch this list grow!
The heart of the code for this demo is in the following method:
var _bindItemDetail = function (jsonData) {
//clear existing bindings
ko.cleanNode($("#itemdetails").get(0));
// observables in selected item.
_viewModel.SelectedItem(ko.mapping.fromJS(jsonData));
// Apply Bindings
ko.applyBindings(_viewModel.SelectedItem, $("#itemdetails").get(0));
};
The essence of what I am trying to achieve is to create a list and details page in one. The list JSON is fetch on initial page load, and the detail JSON is fetched and bound to the "detail" html whenever an edit link is clicked.
In addition to solving the problem, I am trying to understand the behavior, and learn some lessons about how to clean up stale resources properly when using knockout.
Thanks for any help
The problem is that in your _bindItemDetail function, you are reapplying the bindings on your modified view where you already had replicated the elements.
var _bindItemDetail = function (jsonData) {
//clear existing bindings
ko.cleanNode($("#itemdetails").get(0));
// observables in selected item.
_viewModel.SelectedItem(ko.mapping.fromJS(jsonData));
// Apply Bindings
ko.applyBindings(_viewModel.SelectedItem, $("#itemdetails").get(0));
};
ko.cleanNode() merely removes bindings from the elements, it doesn't revert the view back to its initial state. In general, you should only ever call ko.applyBindings on a set of nodes once. Doing it more than once, is just asking for problems.
Frankly you're not really making good use of knockout. The majority of your code is using jquery to handle all the low-level details. The point of using knockout is to not have to worry about those lower level details.
I've adjusted your fiddle a bit to make better use of knockout with less emphasis on using jquery.
In the view:
Used the click binding to handle your Edit click events.
Used the with binding to conditionally show the editor fields. The stopBindings handler is not needed.
In the view model:
Added the click handler editClicked to the view model.
Removed jquery event bindings.
Removed the ko.cleanNode/ko.applyBindings combo you had when binding items. You shouldn't do that and you just don't need it, knockout will handle all that for you.
Updated fiddle

Categories

Resources