How can I overwrite an array using Ractive? - javascript

I have a componet that updates an array on it's parent. Specifically, it takes additions, and creates an entirely new array that has been sorted, overwriting the original array.
var sortedUpdatedDomainNames = updatedProposedDomainNames.sort(sorts.domainName)
// even though we sort them, after setting the value, getting it returns the unsorted items
debugger;
Typing in the debugger here:
sortedUpdatedDomainNames
(4) ["example.com", "www.example.com", "swag.com", "www.swag.com"]
OK that works. The array items are sorted (using sorts.domainName which puts www immediately after parent domains)
await parentComponent.set('order.proposedDomainNames', sortedUpdatedDomainNames)
Here's the first issue: the DOM doesn't update poroperly, some items are duplicated in the DOM even though they're not duplicated in the data.
Running parentComponent.update fixes these duplications, however:
// Work around odd ractive bug where DOM doesn't update properly
// Trigger an update manually using .update()
// TODO: find proper fix!
await parentComponent.update('order.proposedDomainNames');
Her's the second issue: the values are now unsorted (well, they're sorted alphabetically now, which isn't what I want).
parentComponent.get('order.proposedDomainNames');
(4) ["example.com", "swag.com", "www.example.com", "www.swag.com"]
How can I overwrite an array using Ractive?
Please do not submit answers re: ractive.splice() etc - I do not know in advance the index where the data will be inserted, I simply wish to sort the entire array and update it.

Using the deep option for ractive.set() ensures the DOM updates to match the new array values - even though the array is a simple array of primitives.
await parentComponent.set('order.proposedDomainNames', sortedUpdatedDomainNames, { deep: true })
I also tried shuffle, which was suggested, but this does not work and the DOM is still inconsistent with the array value when using shuffle.
Though the issue is solved, I'm still interested in why deep was needed to make the DOM update correctly, so if you have your own answer to that, add it and I'l; accept it!

Related

JavaScript Array-Push?

I'm using charts.js, where I want to add one datarow per minute. Hence to avoid a complete redraw, Im using some ajax and just pushing a new element to the chart.
Pushing VALUES works fine, however, pushing to the label-array shows very strange behaviour. I'v now tried everything from a simple push upto iteratively cloning the whole array, copy all values, replacing the whole array... The result is still the same.
The added element seems to be always end up with index 0, therefore ending up left in the chart, rather than on the right side.
Upon initial pageload, the data that is existing is loaded as a json-array, which works as expected, for example:
var labels = ["16:00", "16:01", "16:02"]
Now, using some ajax, I retrieve a new Dataset for 16:03. Pushing that label to the array like this:
...
labels.push("16:03");
console.log(labels);
...
and inspecting it in the browser afterwards leads to the following strange view:
The stringified representation looks as expected:
(4) ["16:00", "16:01", "16:02", "16:03"]
But when expanding the view in chrome, the result is:
0: "16:03"
1: "16:00"
2: "16:01"
3: "16:02"
So, iterating the array by using index-values obviously leads to a different result than using .toString(). I have no idea what is happening here. I'm mainly confused, why the stringified version looks different than the actual drill down on indexes?
Running a vanilla-example of these steps leads to the desired result. So it has to do something with the "context" of that array. But I have no idea where to start digging ;)
Here's a screenshot
edit:
Following the example over here, it should work like that...
https://www.chartjs.org/docs/latest/developers/updates.html
Comment of #CBroe made me figure it out:
Uppon initial loading, I did not outline the labels explicit, because there i'm having whole objects like {x:"16:00", temp="20", rain="0"} i'm feeding the datarows of chart.js with.
Now, when altering the label-array, chart-js seems to apply the following logic:
Labels-Array is a dedicated Array that EXISTS but is empty if not explicit defined.
In the Getter of that array, Any Labels derived from data-objects are appended to the array.
hence, pushing to the actual array starts with index "0" if it's inititially empty. But looking at the result of the getter then delivers the static array + any required label derived from the data objects given.
Now outlining the labels-array explicit as well, this resolves the issue.

update, instead of replace, list used for ng-repeat

How it is
I have an array of objects called vm.queued_messages (vm is set to this in my controller), and vm.queued_messages is used in ng-repeat to display a list of div's.
When I make an API call which changes the underlying model in the database, I have the API call return a fresh list of queued messages, and in my controller I set the variable vm.queued_messages to that new value, that fresh list of queued messages.
vm.queued_messages = data; // data is the full list of new message objects
The problem
This "full replacement" of vm.queued_messages worked exactly as I wanted, at first. But what I didn't think about was the fact that even objects in that list which had no changes to any properties were leaving and new objects were taking their place. This made no different to the display because the new objects had identical keys and values, they were technically different objects, and thus the div's were secretly leaving and entering every time. THIS MEANS THERE ARE MANY UNWANTED .ng-enter's AND .ng-leave's OCCURRING, which came to my attention when I tried to apply an animation to these div's when they entered or left. I would expect a single div to do the .ng-leave animation on some click, but suddenly a bunch of them did!
My solution attempt
I made a function softRefreshObjectList which updates the keys and values (as well as any entirely new objects, or now absent objects) of an existing list to match those of a new list, WITHOUT REPLACING THE OBJECTS, AS TO MAINTAIN THEIR IDENTITY. I matched objects between the new list and old list by their _id field.
softRefreshObjectList: function(oldObjs, newObjs) {
var resultingObjList = [];
var oldObjsIdMap = {};
_.each(oldObjs, function(obj) {
oldObjsIdMap[obj._id] = obj;
});
_.each(newObjs, function(newObj) {
var correspondingOldObj = oldObjsIdMap[newObj._id];
if (correspondingOldObj) {
// clear out the old obj and put in the keys/values from the new obj
for (var key in correspondingOldObj) delete correspondingOldObj[key];
for (var key in newObj) correspondingOldObj[key] = newObj[key];
resultingObjList.push(correspondingOldObj);
} else {
resultingObjList.push(newObj);
};
});
return resultingObjList;
}
which works for certain things, but with other ng-repeat lists I get odd behavior, I believe because of the delete's and values of the objects being references to other controller variables. Before continuing down this rabbit hole, I want to make this post in case I'm thinking about this wrong, or there's something I'm missing.
My question
Is there a more appropriate way to handle this case, which would either make it easier to handle, or bypass my issue altogether?
Perhaps a way to signal to Angular that these objects are identified by their _id instead of their reference, so that it doesn't make them leave and enter as long as the _id doesn't change.
Or perhaps a better softRefreshObjectList function which iterates through the objects differently, if there's something fishy about how I'm doing it.
Thanks to Petr's comment, I now know about track by for ng-repeat. It's where you can specify a field in your elements that "identifies" that element, so that angular can know when that element really is leaving or entering. In my case, that field was _id, and adding track by message._id to my ng-repeat (ng-repeat="message in ctrl.queued_messages track by message._id") solved my issue perfectly.
Docs here. Search for track by.

Angularfire: behavior of synchronized array

I've been having issues with a synchronized arrays on angularfire. I'm on angularfire 1.1.3 with firebase 2.3.1.
I have a query
var arr = $firebaseArray(ref.limitToFirst(5));
and the behavior I've seen up until now is that when I call
arr.$remove(0)
the next object that would be returned by the query gets loaded into the synchronized array automatically. This essentially makes the array a sliding window over the query response - it always has the same number of elements.
Since last week, that behavior seems to have changed, and I get two different cases:
1: Either arr does get loaded with 5 items, but after calling arr.$remove five times, the array is empty - which would be normal behavior on a JavaScript array, but isn't what I'd been seeing before on an AngularFire synchronized array.
2: Or arr is loaded but then disappears, i.e. in the code:
arr.$loaded(function(){
\\ break
})
If I break in the call back, arr does have five items, corresponding to data on Firebase, but at the end of the Angular digest loop, arr is an empty array.
Demo: This plunker shows behavior 1
So my questions are:
Was I relying on a behavior that was not officially part of the API?
Has that behavior changed?
What explains the last point (the firebase array having items on $loaded but then ending up empty?)
Update
It seems that behavior 2 happens after behavior 1 - more precisely: after getting to an empty synchronized array, if I reload the page, then I get a nonempty array in the callback of arr.$loaded but an empty array in the end.
Could that mean that firebase itself gets "stuck"?
I'll try to to reproduce that in the plunker.
This should be fixed now. Sorry for the inconvenience!

Javascript - removing an element from array

I'm displaying elements from an arraylist in table on the webpage. I want to make sure that once the user press "delete the data", the element in the table is immediately removed so the user does not have to refresh and wait to see the new table. So I'm currently doing it by removing the element from the arraylist, below is the code:
$scope.list= function(Id) {
var position = $scope.list.indexOf(fooCollection.findElementById({Id:Id}));
fooCollection.delete({Id:Id});
if (position>-1) {
$scope.list.splice(position,1);
}
$location.path('/list');
};
But I the position is always -1, so the last item is always removed from the list no matter which element I delete.
I found it strange you we're operating on two different lists to begin with so I assumed you were taking a copy of the initial list. This enabled me to reproduce your bug. On the following line you're trying to find an object that isn't present in your list.
var position = $scope.list.indexOf(fooCollection.findElementById({Id:Id}));
Eventhough we're talking about the same content, these two objects are not the same because:
indexOf compares searchElement to elements of the Array using strict
equality (the same method used by the ===, or triple-equals,
operator).
So there lies your problem. You can see this reproduced on this plunker.
Fixing it the quick way would mean looping over your $scope.list and finding out which element actually has the id that is being passed.
you can use the splice method of javascript which takes two paramete
arrayObject.splice(param1, param2);
param1 -> from this index elements will start removing
param2 -> no of elements will be remove
like if you want to remove only first element and your array object is arrayObject then we can write code as following
arrayObject.splice(0, 1);

How can I call an element from an array created by "document.getElementBytag()"?

I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn't working, but have come up empty.
I want to populate several arrays with different data types from the html, and then, by calling elements from each array by index number, dynamically link and control those elements within functions. I was testing the simple snippet of code below in mootools jsfiddle utility. Trying to call an element from array "region" directly returns "undefined" and trying to return the index number of an element returns the null value of "-1".
I cannot get useful data out of this array. I can think of three possible reasons why, but cannot figure out how to identify what is really happening here:
1. Perhaps this array is not being populated with any data at all.
2. Perhaps it is being populated, but I am misunderstanding what sort of data is gotten by "document.getElementBytag()" and therefore, the data cannot be displayed with the "document.writeln()" statement. (Or am I forced to slavishly create all my arrays?)
3. Perhaps the problem is that an array created in this way is not indexed. (Or is there something I could do to index this array?)
html:
<div>Florida Virginia</div>
<div>California Nevada</div>
<div>Ohio Indiana</div>
<div>New York Massachussetts</div>
<div>Oregon Washington</div>
js:
var region = $$('div');
document.writeln(region[2]);
document.writeln(region.indexOf('Ohio Indiana'));
Thanks for helping a js newbie figure out what is going on in the guts of this array.
$$ will return a list of DOM elements. If you are only interested in the text of those DOM nodes, then extract that bit out first. As #Dimitar pointed out in the comments, calling get on an object of Elements will return an array possibly by iterating over each element in the collection and getting the property in question.
var region = $$('div').get('text');
console.log(region[2]); // Ohio Indiana
console.log(region.indexOf('Ohio Indiana')); // 2
Also use, console.log instead of document.writeln or document.write, reason being that calling this function will clear the entire document and replace it with whatever string was passed in.
See an example.

Categories