Using collection helpers in meteor tabular - javascript

I'm displaying table data using Meteor aldeed:tabular
The tabular initialization code is simple:
this.TabularTables.Customers = new Tabular.Table({
name: "Clients",
collection: this.Customers,
columns: [
{data: "lastName", title: "Name"},
{data: "myMessage()", title: "Message"}
],
});
First field, lastName works perfectly, but adding second field myMessage() causes the problem
I installed dburles:collection-helpers extension and add helper in common code section:
this.Customers = new Mongo.Collection("customers");
this.Customers.helpers({
myMessage: function () {
return "Hi!";
}
});
But still getting error on the client side:
Exception from Tracker recompute function:
debug.js:41 TypeError: a[i[j]] is not a function
at c (jquery.dataTables.min.js:16)
at jquery.dataTables.min.js:17
What might be the problem with my helper function and where should I declare it?

I've done more or less exactly what you have done and it works nicely.
Countries = new Mongo.Collection('countries');
TabularTables = {};
Meteor.isClient && Template.registerHelper('TabularTables', TabularTables);
TabularTables.Countries = new Tabular.Table({
name: "CountriesList",
collection: Countries,
columns: [
{data: 'italian_name', title: 'Italian name'},
{data: 'catalogueName',title: 'Catalogue name'},
{data: "myFunction()", title: 'Wot'}
]
});
Countries.helpers({
myFunction: function () {
return "Hi!";
}
});
The only real difference I can see is this line:
Meteor.isClient && Template.registerHelper('TabularTables', TabularTables);

Finally I found the problem: TabulatTables use collection transformer dburles:collection-helpers to call necessary function, but it confilcts with perak:joins that defines his own helpers

Related

Angular with Kendo, Using Grid Values Asynchronously

Ok I'm pretty sure I know exactly what I need to do here but I'm not sure how to do it. Basically I have a grid that I want to make a key column bind to an array of key/values, which I've done before with kendo (not using Angular) and I know that when I'm creating my key/value array asynchronously then that needs to complete before I can get them show-up with kendo, which I have done using promises before.
So here I have the same issue only angular is also involved. I need to fetch and format an array of data into the format in which a kendo grid column can digest it, so no problem here is my controller code:
var realm = kendo.data.Model.define({
id: 'realmID',
fields: {
realmID: { editable: false, nullable: true }
realmType: { type: 'string', validation: { required: true } }
}
})
var ds1 = kendoHelpers.dataSourceFactory('realms', realm, 'realmID')
var realmType = kendo.data.Model.define({
id: 'realmTypeID',
fields: {
realmTypeID: { editable: false, nullable: true },
name: { type: 'string', validation: { required: true } }
}
})
var ds2 = kendoHelpers.dataSourceFactory('realms/types', realmType, 'realmTypeID')
$scope.mainGridOptions = {
dataSource: ds1,
editable: true,
navigatable: true,
autoBind:false,
toolbar: [
{ name: "create" },
{ name: 'save' },
{ name: 'cancel' }
],
columns: [
{ field: 'realmID', title: 'ID' }
{ field: 'realmTypeID', title: 'Realm Type', editor: realmTypesDDL, values: $scope.realmTypeValues },
{ command: "destroy" }
]
}
$scope.secondGridOptions = {
dataSource: ds2,
editable: true,
navigatable: true,
toolbar: [
{ name: "create" },
{ name: 'save' },
{ name: 'cancel' }
],
columns: [
{ field: 'realmTypeID', title: 'ID' },
{ field: 'name', title: 'Name' }
{ command: "destroy" }
]
}
ds2.fetch(function () {
$scope.realmTypeValues = [{ text: 'Test', value: "24bc2e62-f761-4e70-804c-bc36fdeced3d" }];
//this.data().map(function (v, i) {
// $scope.realmTypeValues.push({ text: v.name, value: v.realmTypeID})
//});
//$scope.mainGridOptions.ds1.read()
});
function realmTypesDDL(container, options) {
$('<input />')
.appendTo(container)
.kendoDropDownList({
dataSource: ds2,
dataTextField: 'name',
dataValueField: 'realmTypeID'
});
}
I made this dataSourceFatory helper method above to return me a basic CRUD kendo dataSource that uses transport and also injects an authorization header which is working fine so don't get hung up on that, ultimately I'm going to be using this data in another grid as well as for reference values for the main grid, but I've hard coded some values that I can use to test with in the ds2.fetch callback.
My HTML is pretty plain:
<div>
<h2>Realms</h2>
<kendo-grid options="mainGridOptions"></kendo-grid>
<h2>Realm Types</h2>
<kendo-grid options="secondGridOptions"></kendo-grid>
</div>
This all works fine and well except I am only seeing the GUID of the realmTypeID in the grid, I click it and the editor is populated correctly so that's good but I want the text value to be displayed instead of the GUID. I'm sure the issue is that the array of values is empty whenever angular is binding to the grid options. My questions are:
How do I either delay this bind operation or manually rebind it after the fetch call?
Is there a better way to handle a situation like this? I try not to expend finite resources for no reason (IE making server calls when unnecessary)
Note: When I move the creation of the text/value array to happen before the grid options, I get the desired behavior I am after
EDIT A work around is to not use the directive to create the grid and instead defer the grid creation until the callback of whatever data your column is dependent on, I was hoping for a more elegant solution but this is better than nothing. So your HTML becomes something like
<h2>Realms</h2>
<div id="realms"></div>
<h2>Realm Types</h2>
<kendo-grid options="secondGridOptions"></kendo-grid>
Then you can create the grid in the fetch callback for example:
ds2.fetch(function () {this.data().map(function (v, i) {
$scope.realmTypeValues.push({ text: v.name, value: v.realmTypeID})
});
$('#realms').kendoGrid($scope.mainGridOptions);
$scope.mainGridOptions.dataSource.fetch()
});
But this doesn't feel very angularish so I'm really hoping for a better solution!
Ok...well I think I hacked this enough and without another suggestion I'm going to go forward with this approach. I'm just going to move the binding logic to the requestEnd event of the second grid so that the values array can be populated right before the binding even. I'm also reworking the values array in this method. It is a bit weird though, I think there is some kendo black magic going on with this array because I can't just set it to a new empty array without it breaking completely...which is why I'm poping everything out prior to repopulating the array. That way when something is deleted or edited in the second grid, the DDL in the first grid is updated in the callback.
function requestEnd(e) {
for (var i = $scope.realmTypeValues.length; i >= 0; i--) $scope.realmTypeValues.pop();
var data;
if (e.type == "read")
data = e.response;
else
data = e.sender.data();
data.map(function (v, i) { $scope.realmTypeValues.push({ text: v.name, value: v.realmTypeID }); });
if ($('#realms').data('kendoGrid') == undefined) {
$('#realms').kendoGrid($scope.mainGridOptions);
}
else
$('#realms').data('kendoGrid').columns[4].values = $scope.realmTypeValues;
}
ds2.bind('requestEnd', requestEnd);
So I'm going to accept my own answer unless anyone has a better approach!

Data Model's "serialize" function not called on property "set"ting

Also asked on Sencha's site here
My data model's "serialize" function is not called when I call
model.set("<fieldName>", <newValue>);
Here's a fiddle
I'm pretty unclear on why the serialize function isn't called...am I missing something, or is this a bug?
(And here's the code from the fiddle)
Ext.application({
name : 'Fiddle',
requires: [
"Ext.data.Store"
],
launch : function() {
var store = Ext.create("Ext.data.Store", {
data: [{Id: 0, Name: "Bill", Props: "{foo: 2, bar:{pan:5}}"}],
fields:[
{name: "Id", type: "int"},
{name: "Name", type: "string"},
{name: "Props",
convert: function(value, record){
console.log("called convert");
return Ext.JSON.decode(value);
},
serialize: function(value, record){
alert("never getting called!! :(");
console.log("sure, i'll put log here too..not getting called though");
return Ext.JSON.encode(value);
}
}
]
});
console.log(store.getAt(0));
var rec = store.getAt(0);
var newProp = {rec:"junk", foo: "orange"};
console.log(newProp);
rec.set("Props",newProp);
}
});
Mappings from source content (JSON/XML) to business model (Ext.data.Model) are not automatically created in ExtJS's data model system. As such, another step is needed to produce this relationship using mapping/associationsor something similar.
I.e. The data model doesn't store the original JSON to read/write from, which is fine for most cases. When a JSON string needs to be updated via ExtJS, one solution is to, on the model, set
convertOnSet
to false, allowing for custom manipulation of the JSON string via extract/update functions on the data model.

Refreshing gridx with server-side data

I'm thinking that I am overlooking something simple - I am so close to making this work. :)
I have a grid that needs to be updated with server information.
Here is the way that it should work:
A user selects an item
Make a JsonRest query with the item ID selected
Update the grid - showing notes relating to item selected
Here is how the grid is setup:
function noteTabSetup() {
var store = JsonRest({target:"//localhost/program/notes", idAttribute:"id"});
var structure = [{ field: 'id', name: 'Id', width: '5em' },
{ field: 'name', name: 'Name', width: '12%' },
{ field: 'description', name: 'Description' }];
var noteGrid = new Grid({
id: 'noteGrid',
pageSize: 20,
store: store,
cacheClass: Cache,
structure: structure,
filterServerMode: true,
selectRowTriggerOnCell: true,
bodyLoadingInfo: "Loading notes ...",
bodyEmptyInfo: "No notes found",
modules: [SingleSort, VirtualVScroller, moveColumn,
selectColumn, dndColumn, selectRow, Filter]}, noteTab);
noteGrid.startup();
When an item is selected, the selected item ID is passed to:
function noteLoad(itemId) {
console.log("In NoteLoad");
var grid = registry.byId("noteGrid");
if (!itemIds || 0 === itemIds.length) { console.log("no ItemId chosen"); }
else {
console.log("In NoteLoad with an itemId");
grid.model.clearCache();
// Error on second run
grid.store.query({ find: "ByItem", item: itemId }).then(function(result) {
grid.setStore(new ItemFileReadStore({data: {items : result}}));
});
grid.body.refresh();
console.log("model: " + grid.rowCount());
};
};
On the first item selected, everything works well - the query fires, and the grid is updated with notes related to the selected item.
On the second item selected, I receive this error from firebug:
TypeError: grid.store.query is not a function
grid.store.query({ find: "ByItem", item: itemIds }).then(function(result) {
-----------------------------------^
Any ideas?! Thank you in advance.
Chris
Thank you for the reply - that makes sense that store was being replaced by ItemFileReadStore. If possible, I would like to use JsonRest directly to update the grid.
I've tried a handful of variations based off of your comment, without luck:
Query fires and result is returned. Grid is not updated:
grid.model.clearCache();
grid.store.query({ find: "ByItem", item: itemIds }).then(function(results){
console.log('notes: ' + results[0].name);
});
grid.body.refresh();
Error: grid.store.fetch is not a function:
grid.store.fetch({ query: { find: "ByItem", item: itemIds }});
Syntax error in Dojo.js (line 15):
grid.store.query({ find: "ByItem", item: itemIds }).then(function(result) {
grid.setStore(new JsonRest({data: {items : result}}));
});
I've done a lot of searches and can't find a good example where the grid is being updated from a JsonRest object. Thank you.
Because the code itself replaces the store the first time.
grid.store.query({ find: "ByItem", item: itemId }).then(function(result) {
grid.setStore(new ItemFileReadStore({data: {items : result}}));
});
Here, the grid's store is initially JsonRest store, which after the query method is run, is replaced by the new ItemFileReadStore object. The mistake here is "query" is not a method of ItemFileReadStore, but the parameter passed to the "fetch" method. Check out some examples from dojo documentation on this.
On the other hand, JsonRest store has the method "query". Hence the contradiction. Change your code accordingly if you want ItemFileReadStore.
eg:-
store.fetch( { query: { name: 'Ice cream' },
onItem: function(item) {
console.log( store.getValue( item, 'name' ) );
console.log( 'cost: ', store.getValue( item, 'cost' ) );
}
});

How to add a new object to an array nested inside an object?

I'm trying to get a handle on using $resource in angularjs and I keep referencing this answer AngularJS $resource RESTful example for good examples. Fetching a record and creating a record work fine, but now i'm trying to add a "section" to an existing mongo record but can't figure it out.
documents collection
{
_id: 'theid',
name: 'My name",
sections: [
{
title: 'First title'
},
{
title: 'Second title'
}
]
}
angular controller snippet
var document = documentService.get({_id: 'theid'});
// TRYING TO ADD $scope.section TO THE SECTIONS ARRAY IN THE VARIABLE document.
//document.sections.push($scope.section); <-- This does NOT work
//document.new_section($scope.section); <-- could do this and then parse it out and insert it in my backend code, but this solution seems hacky and terrible to me.
document.$save(function(section) {
//$scope.document.push(section);
});
documentService
return $resource(SETTINGS.base + '/documents/:id', { id: '#id' },
{
update: { method: 'PUT' }
});
From the link i posted above, If I was just updating the name field, I could just do something like this:
var document = documentService.get({_id: 'theid'});
document.name = "My new name";
document.$save(function(section) {
//$scope.document.push(section);
});
I'm just trying to add an object to a nested array of objects.
Try this:
documentService.get({_id: 'theid'}, function(document) {
document.sections.push($scope.section);
document.$save();
});

Make ember to resolve hasMany relationship when loading

I'm currently facing a big problems for days. I'm using ember simple-auth plugin which provide me a session object accessible through the code or the templates. That session object store the account information such as username, id and rights.
My models are like this :
App.Right = DS.Model.extend({
label: DS.attr('string', { defaultValue: undefined })
});
App.Right.FIXTURES = [
{
id: 1,
label: 'Admin'
}, {
id: 2,
label: 'Manager'
}, {
id: 3,
label: 'User'
}
];
App.User = DS.Model.extend({
username: DS.attr('string'),
rights: DS.hasMany('right', {async: true})
});
App.User.FIXTURES = [
{
id: 1,
username: "Someone",
rights: [1]
}
];
Then I have (as specified on the simple-auth documentation) this setup :
App.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
account: function() {
var userId = this.get('userId');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
...
}
});
Inside one of my view I'm doing this:
this.get('context.session.account.rights').toArray()
but it gives me an empty array. That piece of code is executed inside an Ember.computed property.
The question is how can I resolve the childrens of account before rendering the view ?
Since async: true this.get('context.session.account.rights') will return a promise object so you will have to use this.get('context.session.account.rights').then(... see: http://emberjs.com/api/classes/Ember.RSVP.Promise.html#method_then
Okay so I finally got it to work. It doesn't solve the original question because the original question was completely stupid. It's just IMPOSSIBLE to resolve relationships synchronously when you use the async: true. Trying to resolve it in advance is NOT the solution because you will still not know when it has actually resolved.
So here is the solution:
$.each(this.get('cellContent.buttonList'), function(i, button) {
button.set('hasAccess', false);
this.get('context.session.account').then(function(res) {
res.get('rights').then(function(result) {
button.set('hasAccess', Utils.hasAccess(result.toArray(), button.rights));
});
});
});
Using the following cellContent.buttonList definition:
buttonList: [
Ember.Object.create({
route: 'order',
label: 'Consult',
rights: 'all'
}), Ember.Object.create({
route: 'order.edit',
label: 'Edit',
rights: [1, 2]
})
]
Explanation
We have to use Ember.Object in order to have access to the set method. Using an Ember object is very handy. It allows us to change the value of properties after the render process making the view to update according to the new value you just set.
Because it updates the view, you don't have to care anymore whether your model has resolved or not.
I hope this will help people as much as it helps me.

Categories

Resources