I've spent the last three days trying to figure this out and i hope someone from here could help.
Note regarding setup: I'm working off Ember-Cli therefore my Ember version 1.13.7 and Ember-Data 1.13.8
To learn more about how emberJS works i decided to create a simple blog system that i will use on my own website. The data is loaded from a Firebase database using the Emberfire plugin.
Help: I cannot sort the data i retrieve into a descending order. For example, if i have 5 posts created on Monday, Tues, Wednesday, Thursday and Friday. Each with a unique timestamp in numerical order.
When i retrieve data it shows in this order:
1st ever post (oldest)
2nd ever post
3rd ever post
4th ever post
5th ever post (newest)
i want to reverse the order so my latest blog post appears on top.
I am retrieving data with the following code:
return this.store.find('post');
I can't work out how to use: sortBy which is from Ember itself or the orderBy() which is from firebase/emberfire?
I understand it needs to be inside a controller which will modify the data from the model before presenting it in the view. But can anyone help?
heres some more code:
Attempt at a controller - it doesn't work:
import Ember from 'ember';
export default Ember.ArrayController.extend({
sortedModel : function(){
return this.get('model').sortBy();
}.property('#each')
});
View Template:
{{#each sortedModel as |post|}}
{{#blog-post post=post}}{{/blog-post}}
{{/each}}
{{outlet}}
You need a property to order your posts by. Luckily, Firebase automatically provides such a property. Every item saved to Firebase is automatically given a timestamp at that moment.
In your post model, add a timestamp property like this:
//models/post
export default DS.Model.extend({
//
timestamp: DS.attr('number')
//
});
Now in your controller you can sort by it. You don't need the #each helper because sortBy already works on arrays.
//controllers/posts
import Ember from 'ember';
export default Ember.ArrayController.extend({
sortedModel : function(){
return this.get('model').sortBy('timestamps').reverse();
}
});
I think that should work, but let me know in the comments if you have any trouble!
Since you said your post array is already ordered but the wrong way.
You could use Array.prototype.reverse();
export default Ember.ArrayController.extend // Array and object c are deprecated.
export default Ember.Controller.extend({
sortedModel : function() {
return this.get('model').reverse();
}).property('model')
NB: If this does not work for you (your problem is bigger, but not explained here). I think you should handle the pagination logics in backend.
Instead of
this.store.find('post');
you should be using
this.store.find('post', { page: variable });
Related
I’m trying to create a new dataset type Powerapps Component (PCF). For the moment I am using it to display a view of the records that are available in an entity in Microsoft Dynamics CRM.
I wish to make the view sort itself when I click on the grid column headers (in a similar way that the default CRM grid view does). I'm trying to figure out how to apply a sort to the dataset so that I can refresh it as indicated by the documentation for the dataset.refresh() function:
Refreshes the dataset based on filters, sorting, linking, new column.
New data will be pushed to control in another 'updateView' cycle.
The dataset object does have a “sorting” property, but changing its value and then refreshing the dataset doesn’t seem to have any effect. After the refresh, the sorting property reverts to the value it had before I changed it.
In short, the click handler for the grid header does something like the following bit of code. The refresh gets done and my updateView() function gets called as expected but the sorting was not applied.
dataset.sorting = [{name: 'createdon', sortDirection: 1}];
dataset.refresh();
Any help on getting the dataset sorting to work would be appreciated.
I've been experimenting with PowerApps Component Framework a little bit recently and I can confirm that the following code won't be working:
dataSet.sorting = [ { name: "columnName", sortDirection: 0 } ];
However, I managed to get this one working for me:
dataSet.sorting.pop(); // you may want to clean up the whole collection
dataSet.sorting.push({ name: "columnName", sortDirection: 0 });
I haven't really figured out the reason of this behavior. The sorting array may be implemented as some form of observable collection in the background.
I hope this will guide you to a functioning solution.
The documentation is pretty abysmal here, but here is my best guess from putting a few different pieces of information together.
TLDR: I think there is some kind of extra method that needs to be called on the .sorting property, but I can't find out what it is called. Maybe something like:
dataset.sorting.setSorting({name: 'createdon', sortDirection: 1});
I think you're going to have to try a bunch of likely method names and see what works.
Background and links:
The only reference I could find to dataset.sorting was from here:
In this preview for canvas apps, only a limited set of filtering and sortStatus methods are supported. Filter and sort can be applied to dataset on primary type columns except for the GUID. Filter and sorting can be applied in the same way as in model-driven apps.To retrieve the dataset with filtering and sorting information, call
the methods in context.parameters.[dataset_property_name].filtering
and context.parameters.[dataset_property_name].sorting, then invoke
the context.parameters.[dataset_property_name].refresh().
So it seems that the .filtering and .sorting properties are handled similarly, and that there are some methods attached to them, and only some are supported. That is about as vague as they could make it...
I did find an example of how .filtering is used:
_context.parameters.sampleDataset.filtering.setFilter({
conditions: conditionArray,
filterOperator: 1, // Or
});
There is a brief reference to .setFilter() in the docs, as well as FilterExpression
There is a SortStatus reference, but it doesn't have any corresponding methods explicitly called out. It is possible that this is not yet a supported feature in the public preview, or the documentation is lacking and the name and syntax of the method you need to call on .sorting is not yet documented.
I have domain object named Roll and on the list page i want to show the user all the Roll objects iterating through a list, sorted by entry date.
Here is the code i am using
[rollList: Roll.findAll(sort:"rollDate"){userid==uid}]
rollDate is a field inside the Roll object with data type java.util.Date
Any suggestion on why the output is not sorted by rollDate. When i iterate through the rollList on the gsp page it is not sorted.
Also, on the Roll domain object i have even put this code, but it's still not sorting.
static mapping = {
sort "rollDate"
}
Thank you.
Why aren't you using the dynamic finders?
Roll.findAllByUserid( uid, [ sort:"rollDate", order: 'desc'] )
should work.
The findAll( Map, Closure ) method appeared not a long time ago, perhaps it was not tested well...
You might need to use order in your query as well, then add order to it
[rollList: Roll.findAll(sort:"rollDate", order: 'desc'){userid==uid}]
After trying both the solutions mentioned it still didn't work. So i thought something might be wrong on the front end.
While researching more i found that since i was using jquery data tables it used to re order the sorting. The solutions i found was here
jQuery DataTable rows order
So both the answers above are correct. The issue was actually with jquery data tables.
I am a newbie to knockoutjs. I have searched examples and so far no luck. I have a page that is a data collection form with the values bound using knockout. What I am trying to do is provide the user with a flag letting him know data is modified and that it needs to be saved. In the app a user may pull down the form and display the data from the server and use it only as information. In other cases he may modify that data. I want to display a label that says something like "data has been modified" to the user once any binding has changed plus if he tries to navigate away from the page I want to warn him the changes will be lost. Is there some event I can subscribe to that tells me when any value has been changed in the model?
Thanks,
Terry
Take a look at Ryan Niemeyer's Dirty Flag. It might be what you are looking for. An example of his method can be seen in this jsFiddle.
this.dirtyItems = ko.computed(function() {
return ko.utils.arrayFilter(this.items(), function(item) {
return item.dirtyFlag.isDirty();
});
}, this);
More info can be found in this SO thread: Knockout isDirty example, using dynamic viewmodule from mapping plugin
I have a results page and I am trying to work out how to auto update the page when an external database field is updated. I have seen quite a few examples but they seem to relate to PHP. I have a test that calls various APIs that can take up to an hour to complete. Once the test has completed, it will enter a success or failed message in a database field.
I already have my results page being rendered by django using template tags. I have a table and I have the field I would like to update. There are multiple fields that need update which correspond to each API test.
I have seen this site.. is this the kind of stuff to use? http://www.dajaxproject.com/ Is this an easy task to do? Does anyone have any ideas on how to do this?
Sorry but I don't know where to start on this one.
Cheers - Oli
I decided not to be so bold and just use the old classic page update for this purpose using javascript..
window.onload = setupRefresh;
function setupRefresh() {
setTimeout("refreshPage();", 30000); // milliseconds
}
function refreshPage() {
window.location = location.href;
}
Still open for options however I'm rather inexperienced in django and maybe this was too much to bite off too quickly..
In KnockoutJS, what's the proper way to update an observableArray of JSON data each time an AJAX command is run?
Right now, I'm blanking the array using something like viewmodel.items([]), then repopulating it with the JSON data from the server. Short of using the KnockoutJS mapping plugin (which might be the only way to do this) what is the correct path?
My server logic is going to send some of the same data each time, so I can't just iterate and push the items into the array unless I want duplicates.
//// Adding how I'm doing it today ////
I'm not sure why I'm doing it this way, but this is just how I initially figured out how to update. So basically, like I said before, I get JSON data, then I pass it to something like this:
_model.addIncident = function (json) {
var checked = json.UserTouches > 0 ? true : false;
_model.incidents.push({
id: ko.observable(json.IncidentIDString),
lastTouchId: ko.observable(json.UserLastTouchIDString),
weight: ko.observable(json.Weight),
title: ko.observable(json.Title),
checked: ko.observable(checked),
createdOn: ko.observable(json.IncidentCreatedOn),
servicename: ko.observable(json.Servicename),
inEdit: ko.observable(false),
incidentHistory: ko.observableArray(),
matchScore: ko.observable()
});
};
for each node in the JSON array. As you can see, I've got some custom observables in there that get build with every passing piece of data. Maybe this is the wrong way to go, but it's worked great up until now.
An observableArray is really just a normal observable with some extra methods for array operations.
So, if you want to set the value of an observableArray to a new array, you can just do:
viewModel.items(myNewArray)
The mapping plugin can help you update the existing items in an array with any updates. In this case, your UI will only be updated from any differences.
I know I'm way too late on this one as I found myself stuck in this situation just recently. We can use a simple Javascript util function as a work-around.
If you have already marked _model.incidents as observableArray, you can do something like this when binding the returned JSON data:
eval("_model.incidents("+JSON.stringify(json)+");");
It worked for me. Hope you have created your observable like this:
_model.incidents = ko.observableArray([]);