I'm using Backgrid and I create the Backgrid Object as follows in my Controller:
$.when(recipeRequest).done(function (recipes) {
List.grid = new Backgrid.Grid({
columns: columns, // where columns is defined elsewhere
collection: recipes // recipes is the result of a fetch
})
// Then add it to the Marionette template
}
The above works perfectly and items display as expected
Once the table is displayed we are providing filtering functionality ServerSide as follows:
filterRecipes: function (query) {
// remove any incomplete network requests
_.each(RecipeManager.fetchXhrs, function (r) {
r.abort()
})
// get a filtered set of recipes
var filteredRecipes = RecipeManager.request('recipe:entities', query)
$.when(filteredRecipes).done(function (recipes) {
// this line shows that the result set is being updated as expected with for example 6 results
console.log(recipes)
// setting the new recipe result set to the grid.collection
List.grid.collection = recipes
// here the table rerenders but there are a LOT more results on the table - not 6 as expected
List.grid.render()
})
}
I'm expecting the table to be repopulated with the new collection once the results are returned but my table still shows all the old records.
I'm following the example written here How would I refresh a Backgrid table with new data? So it should redraw the table once the collection has been reset? Or do I need to empty the table first? Any ideas where I might be going wrong?
From backgridjs
Fully reactive. Relevant parts of the grid re-renders automatically upon data changes.
I have not gone through annotated source code but am guessing rerendering is tied to collection events. So, you do not need to explicitly call the render method.
$.when(filteredRecipes).done(function (recipes) {
// this line shows that the result set is being updated as expected with for example 6 results
console.log(recipes)
// setting the new recipe result set to the grid.collection
// considering recipes is backbone collection
// if result is array of objects then List.grid.collection.reset(recipes)
// it should re render the grid
List.grid.collection.reset(recipes.models);
})
Related
Background
I have an angular-meteor app and a collection of business objects in mongodb, e.g.:
{ startDate: new Date(2015, 1, 1), duration: 65, value: 36 }
I want to render this data in different views. One of the views is a graph, another is a list of entries.
The list of entries is easy. Just bind the collection to the model:
vm.entries = $scope.meteorCollection(MyData, false);
In the view I would do:
<div ng-repeat="entry in vm.entries">{{entry.startDate}} - ...</div>
But now for the graph. I want to transform each element into a { x, y } object and give the view that, e.g.:
vm.graphPoints = transformData(getDataHere());
The problem is that the data is not fetched here, in angular-meteor is looks like it is fetched when calling the entry in vm.entries in the view. The kicker is that the transformData method, needs to loop through the data and for each item index into other items to calculate the resulting x, y. Hence I cannot use a simple forEach loop (without having access to the other items in some way).
Question
So how can i fetch the data in the controller - transform it - and still have one-way binding (observing) on new data added to the database?
Thanks
Update
The following code works, but I think there could be performance problems with fetching the whole collection each time there is a change.
$scope.$meteorSubscribe("myData").then(function() {
$scope.$meteorAutorun(function() {
var rawData = MyData.find().fetch();
vm.model.myData = transformData(rawData);
});
});
EDIT:
This is the current solution:
$scope.collectionData = $scope.meteorCollection(MyData, false);
$meteor.autorun($scope, function() {
vm.graphPoints = transformData($scope.collectionData.fetch());
});
There is some missing information. do you wan't to have some kind of model object in the client? if that is correct I think you have to do something like this:
$meteor.autorun($scope, function() {
vm.graphPoints = transformData($scope.meteorCollection(MyData, false));
});
How about using the Collection Helper Meteor package to add the function:
https://github.com/dburles/meteor-collection-helpers/
?
I have got:
Ext.define("catcher.view.Login", {
extend: "Ext.form.Panel",
// creating login form, including selectfield
Store "Tournaments" is created in stores (autoload:true), have its model. Everyting is set.
need to dynamicly fill selectfield (still in view.Login class):
initialize: function(){
var store = Ext.getStore("Tournaments");
var options = new Array();
store.each(function(radek){
options[radek.get("tournament_id")] = radek.get("tournament_name");
});
}
I do not want to use store:"Tournaments" config options, because of later form.submit(); does not send correct data from selectfield.
There is the problem: console.log(store.getCount()); returns 0. Using store.add({ ... }) I can add anything and getCount() returns corrent count (0 + add()).
Weird part: console.log(store) returns whole class including data object with all items inside. And next weird part - If I use the same code in controller, everything works, the Store is loaded properly and I can use mystore.each();
Store loading is asynchronous, by the time you're accessing it, it's not loaded. You need to listen to the store load event.
Something like:
store.on('load', function(storeRef, records, successful){
//Loop through records
}, this);
on() documentation
load event documentation
I have a an "Asset" backbone model that has a custom attribute called "selected". Its custom in the sense that it is not part of the object on the server side. I use to represent which of the list of assets the user has currently selected.
var Asset = Backbone.Model.extend({
defaults: {
selected: false
},
idAttribute: "AssetId"
});
This model is part of a backbone collection that I fetch periodically to get any changes from the server.
The problem I have is that every time I fetch the collection, the collection is doing a reset (I can tell by the listening for the reset event) and hence the value of the selected attribute is wiped out by the data coming in from the ajax request.
The backbone.js documentation seems to suggest that there is a intelligent merge that will solve this problem. I believe I'm doing this in my fetch methods
allAssets.fetch({ update: true ,cache: false});
And I have also set the "idAttribute" field in the model so that the ids of the object coming in can be compared with the objects in the collection.
The way I have solved this is by writing my own Parse method in my collection object
parse: function (response) {
// ensure that the value of the "selected" for any of the models
// is persisted into the model in the new collection
this.each(function(ass) {
if (ass.get("selected")) {
var newSelectedAsset = _.find(response, function(num) { return num.AssetId == ass.get("AssetId"); });
newSelectedAsset.selected = true;
}
});
return response;
}
Is there a better way to do this?
Collection.update (introduced in Backbone 0.9.9) does indeed try to merge existing models, but does so by merging all set attributes in the new model into the old model. If you check Backbone source code, you'll see
if (existing || this._byCid[model.cid]) {
if (options && options.merge && existing) {
existing.set(model.attributes, options);
needsSort = sort;
}
models.splice(i, 1);
continue;
}
All attributes, including defaults, are set, that's why your selected attribute is reset to false. Removing the default value for selected will work as intended: compare http://jsfiddle.net/nikoshr/s5ZXN/ to http://jsfiddle.net/nikoshr/s5ZXN/3/
That said, I wouldn't rely on a model property to store my app state, I would rather move it to a controller somewhere else.
Here I am creating a new Divider with an ID, fetching the Divider, and displaying all attributes and a single attribute:
var divider = new Divider({id: "A"});
divider.fetch();
console.info(divider.attributes);
console.info(divider.get("title"));
The output of console.info(divider.attributes) shows attributes.title as an array with four strings; however; console.info(divider.get("title")) shows null. Can anyone think why it's coming back as null? The only attribute I can get is "id". Also, console.info(divider.attributes.title) also shows null.
Here is my Divider model:
Divider = Backbone.Model.extend({
defaults: {
"id": null,
"title": null,
"description": null
}
}
Let me know if I can provider more information. Thanks!
The Backbone.js fetch is asynchronous, so if you are depending on the attributes to be populated by fetch, you need to make sure to get the attributes after the fetch is complete. Here is an example:
var Divider = new Divider({id: "A"});
divider.fetch({success: function() {
console.info(divider.get("title");
}});
However, I'm still not certain why console.info(divider.attributes) was showing attributes.title with the data, and console.info(divider.attributes.title) was showing as null.
Reference: Backbone.js fetch problem (can't refresh data immediately)
Glad you figured out the async issue. I ran into the same issue as you, and figured out that when the data is being returned, your model's attributes are updated in the console. So at the time you are looking at your console, the fetch method has completed and your model has been updated.
When adding a rows to a grid, and then clicking on it, it gets selected (and highlighted). Then, clicking elsewhere but the new row remains highlighted (so now there are to highlighted rows).
Please, does anyone know what the problem could be? How to make it behave normally, i.e. clicking a row deselects (de-highlights) the other one?
After I reload the page (so the new row is not new anymore), everything works as expected.
Edit: Here's the code for adding rows:
var rec = new store.recordType({
test: 'test'
});
store.add(rec);
Edit 2: The problem seems to be listful: true. If false, it works! But I need it to be true so I'm looking at this further... It looks like as if the IDs went somehow wrong... If the ID would change (I first create the record and then the server returns proper ID, that would also confuse the row selector, no?)
(Note, correct as ExtJS 3.3.1)
First of all, this is my quick and dirty hack. Coincidentally I have my CheckboxSelectionModel extended in my system:-
Kore.ux.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.CheckboxSelectionModel, {
clearSelections : function(fast){
if(this.isLocked()){
return;
}
if(fast !== true){
var ds = this.grid.store,
s = this.selections;
s.each(function(r){
//Hack, ds.indexOfId(r.id) is not correct.
//Inherited problem from Store.reader.realize function
this.deselectRow(ds.indexOf(r));
//this.deselectRow(ds.indexOfId(r.id));
}, this);
s.clear();
}else{
this.selections.clear();
}
this.last = false;
}
});
And this is the place where the clearSelections fails. They try to deselect rows by using ds.indexOfId(r.id) and it will returns -1 because we do not have the index defined remapped.
And this is why we can't find the id:-
http://imageshack.us/photo/my-images/864/ssstore.gif/
Note that the first item in the image is not properly "remapped". This is because we have a problem in the "reMap" function in our Ext.data.Store, read as follow:-
// remap record ids in MixedCollection after records have been realized. #see Store#onCreateRecords, #see DataReader#realize
reMap : function(record) {
if (Ext.isArray(record)) {
for (var i = 0, len = record.length; i < len; i++) {
this.reMap(record[i]);
}
} else {
delete this.data.map[record._phid];
this.data.map[record.id] = record;
var index = this.data.keys.indexOf(record._phid);
this.data.keys.splice(index, 1, record.id);
delete record._phid;
}
}
Apparently, this method fails to get fired (or buggy). Traced further up, this method is called by Ext.data.Store.onCreateRecords
....
this.reader.realize(rs, data);
this.reMap(rs);
....
It does look fine on the first look, but when I trace rs and data, these data magically set to undefined after this.reader.realize function, and hence reMap could not map the phantom record back to the normal record.
I don't know what is wrong with this function, and I don't know how should I overwrite this function in my JsonReader. If any of you happen to be free, do help us trace up further for the culprit that causes this problem
Cheers
Lionel
Looks like to have multi select enabled for you grid. You can configure the selection model of the grid by using the Ext.grid.RowSelectionModel.
Set your selection model to single select by configuring the sm (selection model) in grid panel as show below:
sm: new Ext.grid.RowSelectionModel({singleSelect:true})
Update:
Try reloading the grid using the load method or loadData method of the grid's store. Are you updating the grid on the client side? then maybe you can use loadData method. If you are using to get data from remote.. you can use load method. I use load method to update my grid with new records (after some user actions like add,refresh etc). Or you could simply reload as follows:
grid.getStore().reload();