Firebase: combine query and child event listener - firebase

I have a structure similar to this
{
posts : {
post1Key: {
title : "First Post",
comments : {
comment1Key : {},
comment2Key : {},
comment3Key : {}
}
}
}
...
}
And I'm using the "child updated" events on the key "/posts/post1Key/comments" to listen for new comments.
How can I combine Firebase Query and the event listeners.
Edit: I know this is possible with Firebase, however, I'm using nativescript-plugin-firebase

You can very well combine a Query defined with an orderBy... method and a listener with the on() method: see detailed doc here
For example you could do something like
var query = db.ref('node1').orderByChild('firstName');
query.on('value', function(dataSnapshot) {
dataSnapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
console.log(childKey);
var childData = childSnapshot.val();
console.log(childData);
});
});
Each time a new sub node is added under "node1" you will get the children list ordered by firstName

As at the time of writing, this isn't possible using the nativescript-plugin-firebase. The workaround is to do the sorting/filtering in the eventHandler after you have received the data.
var onChildEvent = function(result) {
//
// Sort: result.value here
//
};
// listen to changes in the /users path
firebase.addChildEventListener(onChildEvent, "/users").then(
function(listenerWrapper) {
var path = listenerWrapper.path;
var listeners = listenerWrapper.listeners; // an Array of listeners added
// you can store the wrapper somewhere to later call 'removeEventListeners'
}
);

Related

Dynamically toggle resource column visibility

I have a FullCalendar scheduler on a webapp which has 2 way databinding for resources and events, all working great. I want to be able to present the user with a dropdown that enables them to toggle the visibility of a column, ideally completely client side.
I have tried a combination of addResource / removeResource however my issue here is that a rerender of the calendar (e.g. when a new event is added) then displays the previously removed resource. I can work around this however would prefer a really simple approach using JS / CSS. I currently cannot find a way to set a resource to not be visible, or to have zero width - is this possible?
There is an easy way to do this:
Store resources in an array variable resourceData.
Create another array called visibleResourceIds to store the ids of any resources you want to show.
In the resources callback function, filter resourceData to only contain the resources where the resource id exists in visibleResourceIds. Return the filtered array and fullcalendar will only add the desired resources for you.
To remove a resource from view, simply remove the resource id from visibleResourceIds and refetchResources. To add the resource back in, add the id to visibleResourceIds and refetchResources. DONE.
JSFiddle
var resourceData = [
{id: "1", title: "R1"},
{id: "2", title: "R2"},
{id: "3", title: "R3"}
];
var visibleResourceIds = ["1", "2", "3"];
// Your button/dropdown will trigger this function. Feed it resourceId.
function toggleResource(resourceId) {
var index = visibleResourceIds.indexOf(resourceId);
if (index !== -1) {
visibleResourceIds.splice(index, 1);
} else {
visibleResourceIds.push(resourceId);
}
$('#calendar').fullCalendar('refetchResources');
}
$('#calendar').fullCalendar({
defaultView: 'agendaDay',
resources: function(callback) {
// Filter resources by whether their id is in visibleResourceIds.
var filteredResources = [];
filteredResources = resourceData.filter(function(x) {
return visibleResourceIds.indexOf(x.id) !== -1;
});
callback(filteredResources);
}
});
I had the same challenge. Instead of a dropdown, I use checkboxes, but the workings will be the same.
My resources are stored in a variable, when I uncheck a box, the resource is removed and the resource's object is added to another array with the resourceId as key, and the index added to the object to restore the object in the same column as it originally was. When re-checking the box, the object is added to the resources array and the resources refetched.
/* retrieve the resources from the server */
var planningResources;
var removedResource = [];
$.ajax({
url: '/planning/resources/',
method: 'get',
success: function (response) {
planningResources = response;
showCalendar();
}
, error: function () {
if (typeof console == "object") {
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
/* create the calendar */
showCalendar = function () {
$('#calendar').fullCalendar({
...
});
}
/* checkbox on click */
$('.resource').click(function() {
var resourceId = $(this).val();
var hideResource = !$(this)[0].checked;
$('.status:checkbox:checked').each(function () {
});
if(hideResource) {
$.each(planningResources, function(index, value){
if( value && value.id == resourceId ) {
value.ndx = index;
removedResource[resourceId] = value;
planningResources.splice(index,1);
return false;
}
});
$('#planningoverview').fullCalendar(
'removeResource',
resourceId
);
}
else {
planningResources.splice(removedResource[resourceId].ndx, 0, removedResource[resourceId]);
$('#planningoverview').fullCalendar('refetchResources');
}
});
showCalendar();
It probably doesn't get first price in a beauty contest, but it works for me ...
Cheers
You can use the resourceColumns option for this. In the column objects you can set the width property to a number of pixels or a percentage. If you pass a function here you can easily handle the width property someplace else. Your hide/show function can then set the width to 0 to hide the column. After that you can trigger reinitView to update the view: $('#calendar').fullCalendar("reinitView");

How to listen to changes in all mongoDB collection

I'm writing a meteor app,
I would like to write an observer which will listen to changes on a remote mongoDB,
Though I would like to write somthing generic which will listen to all Collections and will send the old value and new value. I mean:
var DBCollections = new Meteor.Collection.getall(); -> whats the right way to do this?
var cursor = DBCollection.find();
// watch the cursor for changes
var handle = cursor.observe({
added: function (object) {
var result = Meteor.http.post(
"http://localhost:8080",
{ params: { command: "add_object", value: object} } );
},
changed: function (object) {
oldValue = ??? -> how can I get it?
var result = Meteor.http.post(
"http://localhost:8080",
{ params: {command:"modify_object",oldValue: oldValue,newValue: object}} );
},
removed: function (object) {
var result = Meteor.http.post(
"http://localhost:8080",
{ params: { command: "remove_object",value: object } } );
}
});
so my qustions are like this:
how can I get all collections and observe changes on them?
When object modified how can I get the old value?

Meteor - Script doesn't load Web Audio Buffers properly on refresh / only on certain routes

https://github.com/futureRobin/meteorAudioIssues
Trying to load audio buffers into memory. When I hit localhost:3000/tides or localhost:3000 it loads my buffers into memory with no problems. When I then click through onto a session e.g. localhost:3000/tides/SOMESESSIONID. the buffers have already loaded from the previous state.
However, when I then refresh the page on "localhost:3000/tides/SOMESESSIONID" the buffers don't load properly and the console just logs an array of file path names.
Crucial to app functionality. Any help would be great!
audio.js
//new context for loadKit
var context = new AudioContext();
var audioContext = null;
var scheduleAheadTime = 0;
var current16thNote = 0;
var bpm = 140;
//array of samples to load first.
var samplesToLoad = [
"ghost_kick.wav", "ghost_snare.wav", "zap.wav", "ghost_knock.wav"
];
//create a class called loadKit for loading the sounds.
function loadKit(inputArg) {
//get the array of 6 file paths from input.
this.drumPath = inputArg;
}
//load prototype runs loadsample function.
loadKit.prototype.load = function() {
//when we call load, call loadsample 6 times
//feed it the id and drumPath index value
for (var i = 0; i < 6; i++) {
this.loadSample(i, this.drumPath[i]);
}
};
//array to hold the samples in.
//now loadKitInstance.kickBuffer will hold the buffer.
var buffers = [
function(buffer) {
this.buffer1 = buffer;
},
function(buffer) {
this.buffer2 = buffer;
},
function(buffer) {
this.buffer3 = buffer;
},
function(buffer) {
this.buffer4 = buffer;
},
function(buffer) {
this.buffer5 = buffer;
},
function(buffer) {
this.buffer6 = buffer;
}
];
//load in the samples.
loadKit.prototype.loadSample = function(id, url) {
//new XML request.
var request = new XMLHttpRequest();
//load the url & set response to arraybuffer
request.open("GET", url, true);
request.responseType = "arraybuffer";
//save the result to sample
var sample = this;
//once loaded decode the output & bind to the buffers array
request.onload = function() {
buffers[id].bind("");
context.decodeAudioData(request.response, buffers[id].bind(sample));
}
//send the request.
request.send();
};
//get the list of drums from the beat.json
//load them into a the var 'loadedkit'.
loadDrums = function(listOfSamples) {
var drums = samplesToLoad;
loadedKit = new loadKit(listOfSamples);
loadedKit.load();
console.log(loadedKit);
}
//create a new audio context.
initContext = function() {
try {
//create new Audio Context, global.
sampleContext = new AudioContext();
//create new Tuna instance, global
console.log("web audio context loaded");
} catch (e) {
//if not then alert
alert('Sorry, your browser does not support the Web Audio API.');
}
}
//inital function, ran on window load.
init = function() {
audioContext = new AudioContext();
timerWorker = new Worker("/timer_worker.js");
}
client/main.js
Meteor.startup(function() {
Meteor.startup(function() {
init();
initContext();
});
router.js
Router.route('/', {
template: 'myTemplate',
subscriptions: function() {
this.subscribe('sessions').wait();
},
// Subscriptions or other things we want to "wait" on. This also
// automatically uses the loading hook. That's the only difference between
// this option and the subscriptions option above.
waitOn: function () {
return Meteor.subscribe('sessions');
},
// A data function that can be used to automatically set the data context for
// our layout. This function can also be used by hooks and plugins. For
// example, the "dataNotFound" plugin calls this function to see if it
// returns a null value, and if so, renders the not found template.
data: function () {
return Sessions.findOne({});
},
action: function () {
loadDrums(["ghost_kick.wav", "ghost_snare.wav", "zap.wav", "ghost_knock.wav"]);
// render all templates and regions for this route
this.render();
}
});
Router.route('/tides/:_id',{
template: 'idTemplate',
// a place to put your subscriptions
subscriptions: function() {
this.subscribe('sessions', this.params._id).wait();
},
// Subscriptions or other things we want to "wait" on. This also
// automatically uses the loading hook. That's the only difference between
// this option and the subscriptions option above.
waitOn: function () {
return Meteor.subscribe('sessions');
},
// A data function that can be used to automatically set the data context for
// our layout. This function can also be used by hooks and plugins. For
// example, the "dataNotFound" plugin calls this function to see if it
// returns a null value, and if so, renders the not found template.
data: function (params) {
return Sessions.findOne(this.params._id);
},
action: function () {
console.log("IN ACTION")
console.log(Sessions.findOne(this.params._id));
var samples = Sessions.findOne(this.params._id)["sampleList"];
console.log(samples);
loadDrums(samples);
// render all templates and regions for this route
this.render();
}
})
Okay so i got a reply on the meteor forums!
https://forums.meteor.com/t/script-doesnt-load-web-audio-buffers-properly-on--id-routes/15270
"it looks like your problem is relative paths, it's trying to load your files from localhost:3000/tides/ghost_*.wav if you change line 58 of your router to go up a directory for each file it should work.
loadDrums(["../ghost_kick.wav", "../ghost_snare.wav", "../zap.wav", "../ghost_knock.wav"]);
This did the trick. Seems odd that Meteor can load stuff fine without using '../' in one route but not in another but there we go. Hope this helps someone in the future.

Reactive cursor without updating UI for added record

I am trying to make a newsfeed similar to twitter, where new records are not added to the UI (a button appears with new records count), but updates, change reactively the UI.
I have a collection called NewsItems and I a use a basic reactive cursor (NewsItems.find({})) for my feed. UI is a Blaze template with a each loop.
Subscription is done on a route level (iron router).
Any idea how to implement this kind of behavior using meteor reactivity ?
Thanks,
The trick is to have one more attribute on the NewsItem Collection Say show which is a boolean. NewsItem should have default value of show as false
The Each Loop Should display only Feeds with show == true and button should show the count of all the items with show == false
On Button click update all the elements in the Collection with show == false to show = true
this will make sure that all your feeds are shown .
As and when a new feed comes the Button count will also increase reactively .
Hope this Helps
The idea is to update the local collection (yourCollectionArticles._collection): all articles are {show: false} by default except the first data list (in order not to have a white page).
You detect first collection load using :
Meteor.subscribe("articles", {
onReady: function () {
articlesReady = true;
}
});
Then you observe new added data using
newsItems = NewsItems.find({})
newsItems.observeChanges({
addedBefore: (id, article, before)=> {
if (articlesReady) {
article.show = false;
NewsItems._collection.update({_id: id}, article);
}
else {
article.show = true;
NewsItems._collection.update({_id: id}, article);
}
}
});
Here is a working example: https://gist.github.com/mounibec/9bc90953eb9f3e04a2b3.
Finally I managed it using a session variable for the current date /time:
Template.newsFeed.onCreated(function () {
var tpl = this;
tpl.loaded = new ReactiveVar(0);
tpl.limit = new ReactiveVar(30);
Session.set('newsfeedTime', new Date());
tpl.autorun(function () {
var limit = tpl.limit.get();
var time = Session.get('newsfeedTime');
var subscription = tpl.subscribe('lazyload-newsfeed', time, limit);
var subscriptionCount = tpl.subscribe('news-count', time);
if (subscription.ready()) {
tpl.loaded.set(limit);
}
});
tpl.news = function() {
return NewsItems.find({creationTime: {$lt: Session.get('newsfeedTime')}},
{sort: {relevancy: -1 }},
{limit: tpl.loaded.get()});
},
tpl.countRecent = function() {
return Counts.get('recentCount');
},
tpl.displayCount = function() {
return Counts.get('displayCount');
}
});
Template.newsFeed.events({
'click .load-new': function (evt, tpl) {
evt.preventDefault();
var time = new Date();
var limit = tpl.limit.get();
var countNewsToAdd = tpl.countRecent();
limit += countNewsToAdd;
tpl.limit.set(limit);
Session.set('newsfeedTime', new Date());
}
});

How to show documents from multiple remote publication in the template?

I wish to use Meteor to subscribe a few remote publication via DDP. Then show the documents in one template. Here is what I did:
Posts = {};
var lists = [
{server: "localhost:4000"},
{server: "localhost:5000"}
];
var startup = function () {
_.each(lists, function (list) {
var connection = DDP.connect(`http://${list.server}`);
Posts[`${list.server}`] = new Mongo.Collection('posts', {connection: connection});
connection.subscribe("allPosts");
});
}
startup();
This file is at client folder. Every startup, in this example, at browser I have two client collections Posts["localhost:4000"] and Posts["localhost:5000"], both are same schema. I know this format (Collection[server]) is ugly, please tell me if there is a better way.
Is there a way to show these client collections in the same template with reactive. Like this:
Template.registerHelper("posts", function () {
return Posts.find({}, {sort: {createdAt: -1}});
});
I think Connected Client is a big part of the Meteor. There should be a best practice to solve this problem, right?
Solved.
Connect to multiple servers via DDP, then observe their collections reactive via cursor.observeChanges.
Posts = {};
PostsHandle = {};
// LocalPosts is a local collection lived at browser.
LocalPosts = new Mongo.Collection(null); // null means local
// userId is generated by another Meteor app.
var lists = [
{server: "localhost:4000", userId: [
"hocm8Cd3SjztwtiBr",
"492WZqeqCxrDqfG5u"
]},
{server: "localhost:5000", userId: [
"X3oicwXho45xzmyc6",
"iZY4CdELFN9eQv5sa"
]}
];
var connect = function () {
_.each(lists, function (list) {
console.log("connect:", list.server, list.userId);
var connection = DDP.connect(`http://${list.server}`);
Posts[`${list.server}`] = new Mongo.Collection('posts', {connection: connection}); // 'posts' should be same with remote collection name.
PostsHandle[`${list.server}`] = connection.subscribe("posts", list.userId);
});
};
var observe = function () {
_.each(PostsHandle, function (handle, server) {
Tracker.autorun(function () {
if (handle.ready()) {
console.log(server, handle.ready());
// learn from http://docs.meteor.com/#/full/observe_changes
// thank you cursor.observeChanges
var cursor = Posts[server].find();
var cursorHandle = cursor.observeChanges({
added: function (id, post) {
console.log("added:", id, post);
piece._id = id; // sync post's _id
LocalPosts.insert(post);
},
removed: function (id) {
console.log("removed:", id);
LocalPosts.remove(id);
}
});
}
})
});
}
Template.posts.onCreated(function () {
connect(); // template level subscriptions
});
Template.posts.helpers({
posts: function () {
observe();
return LocalPosts.find({}, {sort: {createdAt: -1}}); // sort reactive
}
});

Resources