I am trying to use CSSTransitionGroup to animate Sentences in a SentenceList. When the "next" button is pressed I want the next Sentence to animate in and the 1st in the list to fadeout. However I get this error message:
Each child in an array should have a unique "key" prop. Check the
render method of Sentence.
I don't understand why that is since when I push Sentence into my List I am passing it a {sentence.id} as a "key" prop. Shouldn't React know that each sentence key is defined as such when rendering it?
I've tried defining the key again in the Sentence render method but to no avail. Are my State changes making React lose track of the current Sentence key?
Thanks for your help!
SentenceList:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var SentenceList = React.createClass({
getInitialState: function() {
return {
sentences: this.props.sentences
}
},
//receives sentence and new blip from Sentence
addBlip: function(sentence, value) {
//see where in the loaded sentences we are
var i = this.state.sentences.indexOf(sentence),
sentences = this.state.sentences,
// callback within a callback (post), the context changes inside the callback so we need to set this to self
self = this;
$.post(
'/sentences/' + sentence.id + '/blips',
{blip: {body: value}},
//set sentence we blipped into as answered
//reset state to reload sentences state after post
function(response) {
sentences[i].answered = true;
// sentences[i].statistics = response.statistics;
// put dummy content first then work it out in the backend to receive the format you want to receive (better to work from front to back)
sentences[i].statistics = [
{word: "butts", frequency: "95%"},
{word: "dogs", frequency: "2%"},
{word: "vegetables", frequency: "1%"},
{word: "sun", frequency: "2%"}
];
self.setState({sentences: sentences});
});
},
//take in a sentence (sent from Sentence) and find current position in loaded sentences and set it to dismissed, then reload list
dismissSentence: function(sentence) {
var i = this.state.sentences.indexOf(sentence),
sentences = this.state.sentences;
sentences[i].dismissed = true;
this.setState({sentences: sentences});
},
//list undismissed sentences and take out the first 3 for display
topThreeRemainingSentences: function() {
var unanswered = _.where(this.state.sentences, {dismissed: false});
return unanswered.slice(0, 3);
},
render: function() {
var remaining = this.topThreeRemainingSentences(),
sentences = [],
index = 0;
//loop through sentences until we have 3 remaining sentences loaded
while (index <= (remaining.length - 1)) {
var sentence = remaining[index];
sentences.push(
<Sentence key={sentence.id}
isActive={index == 0}
isNext={index == 1}
isNnext={index == 2}
onDismiss={this.dismissSentence}
onSubmitBlip={this.addBlip}
details={sentence} />
)
index = index + 1;
}
return (
<ReactCSSTransitionGroup transitionName="animate">
<div>{sentences}</div>
</ReactCSSTransitionGroup>
)
}
});
Sentence:
var Sentence = React.createClass({
getDefaultProps: function() {
return {
onSubmitBlip: function() { console.log(arguments) }
}
},
//pass sentence and new blip to submit function
addBlip: function(e) {
e.preventDefault();
var blipBody = this.refs.newBlip.getDOMNode().value
this.props.onSubmitBlip(this.props.details, blipBody);
},
//send sentence to List to set it to dismissed
dismissSentence: function(e) {
e.preventDefault();
this.props.onDismiss(this.props.details);
},
render: function() {
var phrase = this.props.details.body,
phrase_display = phrase.split("*"),
before = phrase_display[0],
after = phrase_display[1],
positionClass,
stats;
if (this.props.isActive) {
positionClass = "active-sentence"
} else if (this.props.isNext) {
positionClass = "next-sentence"
} else if (this.props.isNnext) {
positionClass = "nnext-sentence"
}
//find stats for sentence if answered from json and push them into array ["word", x%]
if (this.props.details.answered) {
var words = [];
this.props.details.statistics.forEach(function(statistic) {
words.push(<li className="stats-list"><span className="stats-list-word">{statistic.word} </span>
<span className="stats-list-percent">{statistic.frequency} </span> </li>)
})
stats = <div><span className="stats-list-header">others said:</span> {words}</div>
}
if (this.props.isActive) {
nextButton = <div className="next-button" onClick={this.dismissSentence}>V</div>
}
if (this.props.isNext) {
nextButton = <div></div>
}
if (this.props.isNnext) {
nextButton = <div></div>
}
return (
<div className={"blipForm " + positionClass}>
{before}
<form onSubmit={this.addBlip}>
<input type="text"
ref="newBlip" />
</form>
{after}
{nextButton}
<br/>
<ul>{stats}</ul>
</div>
)
}
});
The <li> elements created in the Sentence component's render method need key attributes:
this.props.details.statistics.forEach(function(statistic) {
words.push(<li className="stats-list" key={statistic.id}>...</li>);
});
Related
I would like to show a form through button click in JS vanilla but nothing work. Here is my code
/* ======= Model ======= */
var model = {
currentCat: null,
cats: [
{
clickCount : 0,
name : 'Tabby',
imgSrc : 'img/434164568_fea0ad4013_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/bigtallguy/434164568'
},
{
clickCount : 0,
name : 'Tiger',
imgSrc : 'img/4154543904_6e2428c421_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/xshamx/4154543904'
},
{
clickCount : 0,
name : 'Scaredy',
imgSrc : 'img/22252709_010df3379e_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/kpjas/22252709'
},
{
clickCount : 0,
name : 'Shadow',
imgSrc : 'img/1413379559_412a540d29_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/malfet/1413379559'
},
{
clickCount : 0,
name : 'Sleepy',
imgSrc : 'img/9648464288_2516b35537_z.jpg',
imgAttribution : 'https://www.flickr.com/photos/onesharp/9648464288'
}
]
};
/* ======= Octopus ======= */
var octopus = {
init: function() {
// set our current cat to the first one in the list
model.currentCat = model.cats[0];
// tell our views to initialize
catListView.init();
catView.init();
adminView.init();
},
getCurrentCat: function() {
return model.currentCat;
},
getCats: function() {
return model.cats;
},
// set the currently-selected cat to the object passed in
setCurrentCat: function(cat) {
model.currentCat = cat;
},
// increments the counter for the currently-selected cat
incrementCounter: function() {
model.currentCat.clickCount++;
catView.render();
}
};
/* ======= View ======= */
var catView = {
init: function() {
// store pointers to our DOM elements for easy access later
this.catElem = document.getElementById('cat');
this.catNameElem = document.getElementById('cat-name');
this.catImageElem = document.getElementById('cat-img');
this.countElem = document.getElementById('cat-count');
// on click, increment the current cat's counter
this.catImageElem.addEventListener('click', function(){
octopus.incrementCounter();
});
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
// update the DOM elements with values from the current cat
var currentCat = octopus.getCurrentCat();
this.countElem.textContent = currentCat.clickCount;
this.catNameElem.textContent = currentCat.name;
this.catImageElem.src = currentCat.imgSrc;
}
};
var catListView = {
init: function() {
// store the DOM element for easy access later
this.catListElem = document.getElementById('cat-list');
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
var cat, elem, i;
// get the cats we'll be rendering from the octopus
var cats = octopus.getCats();
// empty the cat list
this.catListElem.innerHTML = '';
// loop over the cats
for (i = 0; i < cats.length; i++) {
// this is the cat we're currently looping over
cat = cats[i];
// make a new cat list item and set its text
elem = document.createElement('li');
elem.textContent = cat.name;
// on click, setCurrentCat and render the catView
// (this uses our closure-in-a-loop trick to connect the value
// of the cat variable to the click event function)
elem.addEventListener('click', (function(catCopy) {
return function() {
octopus.setCurrentCat(catCopy);
catView.render();
};
})(cat));
// finally, add the element to the list
this.catListElem.appendChild(elem);
}
}
};
var adminView = {
init: function() {
this.formElement = document.getElementById('admin-form');
this.buttonAdmin = document.getElementById('admin-button');
console.log(this);
this.render();
},
render: function() {
this.formElement.style.display = 'none';
console.log(this);
this.buttonAdmin.addEventListener('click', (function(form){
return form.style.display = 'block';
})(this.formElement));
console.log(this);
}
};
// make it go!
octopus.init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
</head>
<body>
<ul id="cat-list"></ul>
<div id="cat">
<h2 id="cat-name"></h2>
<div id="cat-count"></div>
<img id="cat-img" src="" alt="cute cat">
</div>
<div>
<button type="button" id="admin-button">Admin</button>
</div>
<div id="admin-form">
<p>Name</p>
<input type="text" name="new-cat-name" value="">
<p>Img URL</p>
<input type="text" name="new-img-url" value="">
<p># Count</p>
<input type="text" name="new-count-number" value="">
<br>
<button type="button" name="save">Save</button>
<button type="button" name="cancel">Cancel</button>
</div>
<script src="js/app.js"></script>
<script>
if(!document.getElementById('admin-button').active){
document.getElementById('admin-form').style.display ='none';
}
</script>
</body>
</html>
I don't understand why the form (#admin-form) is shown when the page is loaded, it should be shown only when the button (#admin-button) is clicked.
Update: I added the script to hide the form in HTML file.
Here's your problem:
this.buttonAdmin.addEventListener('click', (function(form){
return form.style.display = 'block';
})(this.formElement));
You wrap the handler function in parens and call it immediately. Try:
this.buttonAdmin.addEventListener('click', function(){
this.formElement.style.display = 'block';
}.bind(this));
Or, if you don't want to use bind for whatever reason:
var form = this.formElement;
this.buttonAdmin.addEventListener('click', function(){
form.style.display = 'block';
});
I am having issues with pagination I've implemented. Pagination works based on server-sided publish skip & limit filter.
Issue #1.
If I perform a specific user search the very first page will be blank.
At that state skip is set to 0, limit is always 20.
If I perform a find().fetch() I get 20 elements, but they are all for a different user.
Issue #2 Me going to next page (skip+10) gives me a few more elements
Doing it again gives even more results
and finally being out of data, and going to next page just removes 10 results, leaving 10 shown
This is a very odd behavior.
Server-sided publish
Meteor.publish('overtime', function(opt){
if (!Roles.userIsInRole(this.userId, 'admin')) {
return Overtime.find({userId: this.userId}, opt);
} else {
return Overtime.find({}, opt);
}
});
Client-sided subscription
var defaultSkipStep = 10;
var defaultLimit = 20;
Template.triphtml.onCreated(function(){
var instance = this;
Session.set('limit',defaultLimit);
instance.autorun(function(){
instance.subscribe('overtime', {skip:(Session.get('overSkip')||0), limit:(Session.get('limit')||defaultLimit), sort: {createdAt: -1}});
instance.subscribe('trips', {skip:(Session.get('tripSkip')||0), limit:(Session.get('limit')||defaultLimit), sort: {createdAt: -1}});
});
Next page click event
"click .nxtpage_over": function(event, template){
Session.set('overSkip', (Session.get('overSkip') || 0) + defaultSkipStep);
Session.set('limit', 20);
},
Submit event
https://pastebin.com/btYCSQBD
Query that user sees
main.js (client)
https://pastebin.com/tWakPDT1
main.html
https://pastebin.com/4uMVFsNG
Any idea how to make it so that when I perform search for a specific user I get all 20 results just for that user, and next page gives me NEXT 20 elements, not showing any one the 20 I've just seen.
Use below code for pagination. It is very ideal code, easy to understand and implement.
SERVER PUBLISH:
Meteor.publish('Students', function (str, toSkip, tillLimit) {
var regex = new RegExp(str, 'i');
var data = Students.find( {
$or:[
{"_id": {'$regex' : regex}},
{"username": {'$regex' : regex}}
]
},
{sort: {'time': -1}, skip: toSkip, limit : tillLimit});
return data;
});
Meteor.publish('StudentsTotalCount', function (str) {
var regex = new RegExp(str, 'i');
Counts.publish(this, "StudentsTotalCount", Students.find({
$or:[
{"_id": {'$regex' : regex}},
{"username": {'$regex' : regex}}
]
});
);
});
str is global search text from client side. Now, Since the user will click on next and previous button frequently. On the client side the Subscription must be reactive. For that you can you below code.
CLIENT SUBSCRIBE:
Inside some App_ShowStudents.js file, you can create subscription as below;
Template.App_ShowStudents.onCreated(function(){
this.userId = new ReactiveVar("");
this.filterCriteria = new ReactiveVar("");
//PAGINATION
this.enablePrevious = new ReactiveVar(false);
this.enableNext = new ReactiveVar(true);
this.skip = new ReactiveVar(0);
this.diff = new ReactiveVar(0);
this.total = new ReactiveVar(0);
this.limit = new ReactiveVar(10);
this.autorun(() => {
Meteor.subscribe('Students', this.filterCriteria.get(), this.skip.get(), this.limit.get());
Meteor.subscribe('StudentsTotalCount', this.filterCriteria.get(), this.role.get());
});
});
HELPERS:
Template.App_ShowStudents.helpers({
students(){
return Students.findOne({}); // this will always be less or equal to 10.
},
skip(){
return Template.instance().skip.get();
},
diff(){
var instance = Template.instance();
var add = instance.skip.get() + instance.limit.get();
var total = instance.total.get();
var diff = (add >= total ? total : add);
instance.diff.set(diff);
return instance.diff.get();
},
total(){
Template.instance().total.set(Counts.get('StudentsTotalCount'));
return Template.instance().total.get();
}
});
total actually must be reactive and should give only count as per your search criteria, so we had a seperate publish on server.
EVENTS:
Template.App_ShowStudents.events({
'click .previous': function (event, template) {
event.preventDefault();
if(template.diff.get() > template.limit.get()){
template.skip.set(template.skip.get() - template.limit.get());
}
},
'click .next': function (event, template) {
event.preventDefault();
if(template.diff.get() < template.total.get()){
template.skip.set(template.skip.get() + template.limit.get());
}
},
'input #searchData': function( event, template ) {
if ( $( event.target ).val()) { // has some value.
template.filterCriteria.set( $( event.target ).val() );
} else {
template.filterCriteria.set( "" );
}
console.log(template.filterCriteria.get());
},
});
App_ShowStudents.html
<template name="App_ShowStudents">
{{#if Template.subscriptionsReady}}
<body>
<input type="text" id="searchData" class="form-control input-lg" placeholder="Search ID, Username" />
Showing {{skip}} - {{diff}} of {{total}}
{{#each students}}
...
{{/each}}
<ul>
<li>Previous</li>
<li>Next</li>
</ul>
</body>
{{else}}
Please wait...
{{/if}}
</template>
I'm trying to make a dynamic "favorites" toggle-button.
When clicking the button, it should add the selected player to the users favorite-list. If the player is already favorited, it should remove it.
I've also tried to iterate through the favorites, to check if a player is already favorited. If true, it colors the favorite star gold.
A few problems here. My for loop for checking seems to be working properly as long as the array only contains one item. But as soon as I try adding more, the gold icon is only gold colored on the last player added to favorites. So the check only finds one favorite at a time, and I can add a player to favorites many times, as long as I vary the players I add.
If someone could point me in the right direction and help me understand why my loop isn't working correctly, that would be awesome!
http://codepen.io/utrolig/pen/LNgRwv
Javascript
angular.module('test', [])
.controller('TestController', function($scope){
$scope.players = [
{
uniqueid: "gem",
name: "Ole Christian",
cake: false,
},{
uniqueid: "utrolig",
name: "Stian",
cake: false,
},{
uniqueid: "drozo",
name: "Adrian",
cake: false,
}
];
$scope.user = {
name: "Stian",
username: "stiba",
favorites: [{uniqueid: "drozo"}],
}
$scope.checkFavorite = function(id){
fav = $scope.user.favorites;
var exists;
for (var i=0; i < fav.length; i++){
if(fav[i].uniqueid == id){
exists = true;
} else {
exists = false;
}
}
return exists;
}
$scope.toggleFavorite = function(id){
fav = $scope.user.favorites;
if(fav.length === 0){
var newfav = {uniqueid: id};
fav.push(newfav);
} else {
if($scope.checkFavorite(id) === true){
for(var i = 0; i < fav.length; i++){
if (fav[i].uniqueid === id) fav.splice(i, 1);
}
} else if ($scope.checkFavorite(id) === false) {
var newfav = {uniqueid: id};
fav.push(newfav)
} else {
console.log('Error!');
}
}
}
$scope.isFavorited = function(){
return true;
};
})
HTML
<body ng-app="test">
<div class="container" ng-controller="TestController">
<h3>Players</h3>
<div ng-repeat="player in players" class="player-cont">
<div class="player">
<div class="favorite" ng-click="toggleFavorite(player.uniqueid)" ng-class="{'active': checkFavorite(player.uniqueid)}">
<i class="material-icons">star</i>
</div>
<i class="material-icons player-icon">person</i>
</div>
<div>
<p ng-bind="player.uniqueid"></p>
<p ng-bind="player.name"></p>
</div>
</div>
<h3>Favorites</h3>
<div ng-repeat="favorite in user.favorites track by $index">
<h5>{{favorite.uniqueid}}</h5>
</div>
<p class="user">
{{user.favorites}}
</p>
</div>
</body>
There's a couple of errors in your code.
The first is checkFavorite, if you examine the code you'll see that only the last item is actually compared to id, since the exists flag is updated for each item. You need to "short circuit" the loop and return true as soon as you find a value.
btw, is* is a common name convention for checking boolean values.
$scope.isFavorite = function(id){
var fav = $scope.user.favorites;
for (var i=0; i < fav.length; i++){
if(fav[i].uniqueid == id){
return true;
}
}
return false;
}
Your toggle is also very verbose, if you "reduce" the code you end up with something like this
$scope.toggleFavorite = function(id){
var fav = $scope.user.favorites;
// no previous items, remove, OK
if(fav.length === 0) {
var newfav = {uniqueid: id};
fav.push(newfav);
return;
}
// if already a favorite, uncheck/remove
if($scope.isFavorite(id)) {
for(var i = 0; i < fav.length; i++){
if (fav[i].uniqueid === id) fav.splice(i, 1);
}
}
// otherwise add the item
// remember, isFavorite returns true of false, there is no third state
else { // if ($scope.isFavorite(id) === false) {
var newfav = {uniqueid: id};
fav.push(newfav)
}
}
This can be edited further, since the isFavorite function will return false if the list is empty, i.e. no need for the first if
$scope.toggleFavorite = function(id){
var fav = $scope.user.favorites;
// if already a favorite, uncheck/remove
if($scope.isFavorite(id)) {
for(var i = 0; i < fav.length; i++){
if (fav[i].uniqueid === id) {
fav.splice(i, 1);
// unless the item exists more than once, break the loop
break;
}
}
}
// otherwise add the item
else {
var newfav = {uniqueid: id};
fav.push(newfav)
}
}
Am struggling hard to bind an array object with list of span values using watcher in Angularjs.
It is partially working, when i input span elements, an array automatically gets created for each span and when I remove any span element -> respective row from the existing array gets deleted and all the other rows gets realigned correctly(without disturbing the value and name).
The problem is when I remove a span element and reenter it using my input text, it is not getting added to my array. So, after removing one span element, and enter any new element - these new values are not getting appended to my array.
DemoCode fiddle link
What am I missing in my code?
How can I get reinserted spans to be appended to the existing array object without disturbing the values of leftover rows (name and values of array)?
Please note that values will get changed any time as per a chart.
This is the code am using:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
Am giving another try, checking my luck on SO... I tried using another object to track the data while appending, but found difficult.
You should be using the scope as a way to bridge the full array and the tags. use ng-repeat to show the tags, and use the input model to push it into the main array that's showing the tags. I got it started for you here: http://jsfiddle.net/d5ah88mh/9/
function rdCtrl($scope){
$scope.dataset = [];
$scope.inputVal = "";
$scope.removeData = function(index){
$scope.dataset.splice(index, 1);
redoIndexes($scope.dataset);
}
$scope.addToData = function(){
$scope.dataset.push(
{"id": $scope.dataset.length+1,
"name": $scope.inputVal,
"value": 3}
);
$scope.inputVal = "";
redoIndexes($scope.dataset);
}
function redoIndexes(dataset){
for(i=0; i<dataset.length; i++){
$scope.dataset[i].id = i;
}
}
}
<div ng-app>
<div ng-controller="rdCtrl">
<div id="tags" style="border:none;width:370px;margin-left:300px;">
<span class="tag" style="padding:10px;background-color:#808080;margin-left:10px;margin-right:10px;" ng-repeat="data in dataset" id="4" ng-click="removeData($index)">{{data.name}}</span>
<div>
<input type="text" style="margin-left:-5px;" id="inptags" value="" placeholder="Add ur 5 main categories (enter ,)" ng-model="inputVal" />
<button type="submit" ng-click="addToData()">Submit</button>
<img src="../../../static/app/img/accept.png" ng-click="assign()" id="assign" style="cursor:pointer;display:none" />
</div>
</div>
<div id="status" style="margin-top:100px;"></div>
</div>
</div>
I'm using Firebase-util's intersection function to find all the comments for a given link. This seems to work fine the first time I call the join, but it doesn't seem to properly notify my value callback when I remove the contents of the database and replace them again. Shouldn't the references keep working as long as the resource path remains the same?
Run this example. When you click the button, it erases and recreates the data. As you can see, the comment list is not repopulated after the data gets recreated.
<link rel="import" href="https://www.polymer-project.org/components/polymer/polymer.html">
<script src="http://cdn.firebase.com/v0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebase-util/0.1.0/firebase-util.min.js"></script>
<polymer-element name="my-element">
<template>
<h1>Test of Firebase-util.intersection</h1>
<div>
<button on-click={{initializeFirebase}}>Reset data</button>
</div>
<ul>
<template repeat="{{rootComment in comments}}">
<li>{{rootComment.comment.content}}
<ul>
<template repeat="{{subComment in rootComment.children}}">
<li>{{subComment.comment.content}}
<ul>
<template repeat="{{subSubComment in subComment.children}}">
<li>{{subSubComment.comment.content}}</li>
</template>
</ul>
</li>
</template>
</ul>
</li>
</template>
</ul>
</template>
<script>
Polymer('my-element', {
ready: function() {
var sanitizeUrl = function(url) {
return encodeURIComponent(url).replace(/\./g, '%ZZ');
};
var baseUrl = "https://nested-comments-test.firebaseio.com";
var linkUrl = baseUrl +
'/links/' +
sanitizeUrl(document.URL) +
'/comments';
var commentsUrl = baseUrl + '/comments';
var root = new Firebase(baseUrl);
this.initializeFirebase = function() {
function addLink(url, callback) {
var key = sanitizeUrl(url),
newLink = {
url: url,
createdAt: Firebase.ServerValue.TIMESTAMP
};
root.child('/links/' + key).update(newLink);
callback(key);
}
function addComment(attributes, callback) {
return root.child('/comments').push(attributes, callback);
}
function onCommentAdded(childSnapshot) {
var newCommentId = childSnapshot.name(),
attributes = {},
link = childSnapshot.val().link,
url = '/links/' + link + '/comments';
attributes[newCommentId] = true;
root.child(url).update(attributes);
}
root.remove(function() {
root.child('/comments').on('child_added', onCommentAdded);
addLink(document.URL, function(link) {
var attributes = {
link: link,
content: "This is the first comment."
},
firstCommentId, secondCommentId;
firstCommentId = addComment(attributes).name();
attributes = {
link: link,
content: "This is a reply to the first.",
replyToCommentId: firstCommentId
};
secondCommentId = addComment(attributes).name();
attributes = {
link: link,
content: "This is a reply to the second.",
replyToCommentId: secondCommentId
};
addComment(attributes);
attributes = {
link: link,
content: "This is another reply to the first.",
replyToCommentId: firstCommentId
};
addComment(attributes);
});
});
};
this.initializeFirebase();
var findChildrenForComment = function(snapshot, parentCommentId) {
var returnVal = [];
snapshot.forEach(function(snap) {
var comment = snap.val(),
commentId = snap.name();
if (comment.replyToCommentId === parentCommentId) {
var children = findChildrenForComment(snapshot, commentId);
var obj = {
commentId: commentId,
comment: comment,
parentId: parentCommentId
};
if (children.length) {
obj.children = children;
}
returnVal.push(obj);
}
});
return returnVal;
};
this.ref = Firebase.util.intersection(
new Firebase(linkUrl),
new Firebase(commentsUrl)
);
this.comments = {};
var that = this;
this.ref.on('value', function(snapshot) {
that.comments = findChildrenForComment(snapshot);
});
}
});
</script>
</polymer-element>
<my-element></my-element>
Apparently deleting a path entirely causes all callbacks on it to be canceled. The workaround for this behavior is to remove children one at a time rather than deleting their parent path.