Meteor template isn't rendering properly - javascript

I'm building a notifications page, where the user can see which posts have comments, and I want to display the date of each post, but it's not working.
Here is the code:
<template name="notification">
<li>Someone commented your post, {{postDate}} </li>
</template>
Template.notification.helpers({
notificationPostPath: function() {
return Router.routes.PostPage.path({_id: this.postId});
},
post: function () {
return Post.findOne({_id: this.postId});
},
postDate: function() {
return moment(post.submitted).format('dddd, MMMM Do');
}
});
The console prints this: Exception from Deps recompute: ReferenceError: post is not defined.
Thanks in advance

I assume the error is being flagged on the following line:
return moment(post.submitted).format('dddd, MMMM Do');
Note that you can't refer to helpers from within other helpers like that (and anyway, post is a function) - you need too add another line at the start of the postDate helper like this:
var post = Post.findOne({_id: this.postId});

Related

Laravel- How to "catch" a variable with Javascript passed to a blade.php view

so i'm currently working on a project and i want to add a calendar to one view, i'm using FullCalendar, the calendar is shown in the view but i'm currently trying to add events to that calendar, those events are going to be "pulled" from my database into the calendar to be displayed, now the problem is that when i pass the array with the events to the blade.php view that contains the calendar a error comes up saying that the variable "events" is undefined and i don't know if i'm doing something wrong, here's the code:
RegisteredUserController.php
$events = array();
$citas = Cita::all();
foreach($citas as $cita){
$events[] = [
'title' => $cita->paciente_id,
'start' => $cita->hora_de_inicio,
'end' => $cita->hora_de_finalizacion
];
}
return redirect(RouteServiceProvider::HOME)->with(['events' => $events]);
RouteServiceProvider.php
public const HOME = '/home';
homeView.blade.php (This is where i get the error, in the line where i assign it to citas)
<div id="calendar">
</div>
<script>
$(document).ready(function(){
var citas = #json($events);
$('#calendar').fullCalendar({
header: {
left: 'month, agendaWeek, agendaDay',
},
events: citas
})
});
</script>
routes / web.php
Route::get('/home', function (){
return view('homeView');
})->name('homeView');
Not sure if it's helpful but i'm using Laravel's Breeze to handle the authentication of users, so when an user is aunthenticated they're redirected to the page where the calendar is.
i've tried the following
RegisteredUserController.php
return redirect(RouteServiceProvider::HOME, compact('events));
This one makes the whole calendar disappear:
homeView.blade.php
var citas = {{ Session::get('events') }};
Thank you in advance.
the return should be like this
return view('path_of_the_blade', compact('events'));
So then in View, you can use
<script>
var citas = #json($events);
</script>
On you controller, why don't you just simply use:
return view('homeView')->with(['events' => $events]);
or simplier:
return view('homeView', compact('events'));
This would surely pass the variable events on the blade file.
Then on your blade file, you will just reference it as:
var citas = {{ $events }};

Angular select with ngModel gives me [$rootScope:inprog] error

I am not very good with angular, but i know some basics. Now, I have access points and want to assign them to a building. I can select this building with a <select>. I have written a simple controller, but it wont work. What am I making wrong, i cant find a solution.
Edit 1:
I can see the option fields (they are 3). But after I select one of these, my browser console throws the exception
Edit 2: Plunkr -> https://plnkr.co/edit/EIPs8yVlTSaYQ0EuZLTb (i hope, this url works) .. When you click on "Neuer Access-Point" the error will occur, after you select something on "Gebäude"
Select field
<select ng-model="$ctrl.input.building">
<option ng-repeat="building in $ctrl.buildings" ng-value="building.id" ng-bind="building.name"></option>
</select>
Controller
(function () {
function createController(Building) {
var ctrl = this;
ctrl.buildings = null;
ctrl.input = {
host: '',
desc: '',
web: '',
building: ''
};
ctrl.$onInit = function () {
Building.getAll().then(function (res) {
if (res.status >= 200 && res.status < 300) {
ctrl.buildings = res.data;
}
});
};
}
angular.module('app').controller('CreateController', createController)
})();
Error
angular.js:14791 Error: [$rootScope:inprog] http://errors.angularjs.org/1.6.8/$rootScope/inprog?p0=%24apply
at angular.js:88
at p (angular.js:18897)
at m.$digest (angular.js:18319)
at m.$apply (angular.js:18640)
at Object.$$debounceViewValueCommit (angular.js:29394)
at Object.$setViewValue (angular.js:29372)
at angular.js:33596
at m.$eval (angular.js:18533)
at m.$apply (angular.js:18632)
at HTMLSelectElement.<anonymous> (angular.js:33595)
Here is the issue with your code.
<div id="wrapper" ng-app="accessPoints" ng-controller="RootController **as $root**">
Change it to simply
ng-controller="RootController as anythingButNot$root"
or even just ng-controller="RootController"
Declaring any controller as $root is creating mess for you. $root is the root level controller of your application. Inside your html if you declare any controller as $root, it tries to overwrite $root, creating trouble with digest cycle, hence you are getting the error.
Link to updated plunk => https://plnkr.co/edit/UcJHVmekMqWMXJBnv2Cu?p=preview

Vue.js - Trouble displaying results from API call in component

Experimenting with Vue.js, trying to display results from a Wikipedia API call in a component using the v-for directive, but something is not working on the back end and I don't know what it is.
Link to the jsFiddle
HTML
<div id="app">
<input type="text" v-model="searchTerm" v-on:keyup="getResults">
<searchResult
v-for="item in results"
v-bind:result="item"
v-bind:key="item.key"
></searchResult>
</div>
Javascript
new Vue({
el: '#app',
data: {
api: "https://en.wikipedia.org/w/api.php?",
searchTerm: 'Ron',
searchDataString: "action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy",
searchCall: this.api+""+this.searchDataString,
results: []
},
methods: {
getResults() {
this.searchCall = this.api+"action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy";
//console.log( this.searchCall );
axios.post( this.searchCall )
.then(response => { this.processResults(response.data) });
},
processResults(data) {
//console.log( data );
for(var i = 0; i < data[1].length; i++) {
var resultItem = { key:i, link:data[3][i], name:data[1], description:data[2][i] };
this.results.push(resultItem);
console.log(resultItem);
}
}
}
});
Vue.component( "searchResult", {
props:['result'],
template: "<a target='_blank' href='{{ result.link }}'><div class='search-result'><h3>{{ result.name }}</h3><p>{{ result.description }}</p><div></a>"
});
The two issues on my mind are
the error message that shows in the console when typing input, and
that the array of results is creating empty objects instead of passing the data
When I look at the array in the console, all it shows are getters and setters. I'm new to this, so maybe that's what it's supposed to be doing.
I'm so close to getting this working, but I'm at my wits end, help is much appreciated.
The problem with your code is that html tags aren't case sensitive so naming a component searchResult causes issues. If you need to use searchResult, you'll have to use <search-result> in your template. I find it better just to avoid the problem altogether and give components lower-case names. Here are docs about the issue: https://v2.vuejs.org/v2/guide/components.html#Component-Naming-Conventions
You mentioned "the error message that shows in the console when typing input". I didn't get any errors copying and pasting your code (other than forgetting to include axios). What error are you getting?

PolymerJS POST JSON formatting

I am trying to POST using PolymerJS ajax-forms and I encounter a weird JSON format error. Can someone tell me why the quotes are missing around the keys? The only workaround I can think of is manually constructing the body with the quotes around the keys.
Code Snippet :
How I receive the values (rest are the same with the ids changed):
<div>
<paper-input label="Title" id="course-title" floatingLabel value="{{item.title}}"></paper-input>
</div>
<access-core-ajax
auto = "false"
url="domain/courses"
response="{{response}}"
method="post"
id="postCourse"
contentType="application/json"
headers='{"Accept": "application/json", "Content-Type":"application/json"}',
body = "{{item}}">
<template id="get-response-template" repeat="{{item in response.entries}}">
<p>Errors</p>
</template>
</access-core-ajax>
Polymer('create-new-course-page',{
domReady: function() {
console.log("Log: create-new-courses-page - Looks like we are domReady");
},
created: function() {
console.log("Item initialized");
this.item = {};
this.data={};
},
createNewCourse: function(event) {
console.log("HERE IS BODY", this.item);
this.$.postCourse.go();
}
And the JSON is see on the log:
{
title: "WRU",
// rest of key & values, where the keys are without the ""
}
You need to turn the body into a JSON string first. JSON.stringify can help.
...
createNewCourse: function(e) {
this.$.postCourse.body = JSON.stringify(this.item);
this.$.postCourse.go();
}
You may need to remove the body attribute here. You can also remove that auto attribute since by default it is false.

Grouping by date using Meteor

I would like to group posts by date, using Meteor, and still retain its characteristic reactivity. I don't know it that is really possible.
I am developing a website based on the Microscope, following the instructions from the book Discover Meteor, but I'm having a hard time making small changes, because I do not have experience with Meteor.
I made small adjustments to the original code book, but nothing that really change its original structure.
What I need to do is group posts by date so they look like this:
Today
Post 7
Post 6
Post 5
Yesterday
Post 4
Post 3
08/11/2014
Post 2
Post 1
My current code is structured as follows:
/client/view/posts/posts_list.js
Template.postsList.helpers({
posts: function() {
return Posts.find({}, {sort: {submittedDate: -1}});
}
});
/client/view/posts/posts_list.html
<template name="postsList">
<div class="posts">
{{#each posts}}
{{> postItem}}
{{/each}}
{{#if nextPath}}
<a class="load-more" href="{{nextPath}}">Show more</a>
{{/if}}
</div>
</template>
/client/view/posts/post_item.js
Template.postItem.helpers({
ownPost: function () {
return this.userId == Meteor.userId();
},
});
/client/view/posts/post_item.html
<template name="postItem">
<div class="post">
<div class="post-content">
<h3>{{title}}<span>{{description}}</span></h3>
</div>
<div class="post-comments">
{{commentsCount}} comments
</div>
{{#if ownPost}}
Edit
{{/if}}
</div>
</template>
/collections/posts.js
Posts = new Meteor.Collection('posts');
Posts.allow({
update: ownsDocument,
remove: ownsDocument
});
Meteor.methods({
post: function(postAttributes) {
var user = Meteor.user(), postWithSameLink = Posts.findOne({url: postAttributes.url});
if(!user)
throw new Meteor.Error(401, "You need to be a registered user to do this");
if(!postAttributes.title)
throw new Meteor.Error(422, "Please, fill the name field");
if(!postAttributes.description)
throw new Meteor.Error(422, "Please, fill the description field");
if(!postAttributes.url)
throw new Meteor.Error(422, "Please, fill the URL field");
if(postAttributes.url && postWithSameLink) {
throw new Meteor.Error(302, "This URL already exist", postWithSameLink._id);
}
var post = _.extend(_.pick(postAttributes, 'url', 'title', 'description'), {
userId: user._id,
author: user.username,
submittedDate: new Date().getTime(),
commentsCount: 0
});
var postId = Posts.insert(post);
return postId;
}
});
/server/publications.js
Meteor.publish('posts', function(options) {
return Posts.find({}, options);
});
Meteor.publish('singlePost', function(id) {
return id && Posts.find(id);
});
Meteor.publish('comments', function(postId) {
return Comments.find({postId: postId});
});
Meteor.publish('notifications', function() {
return Notifications.find({userId: this.userId});
});
I tried several solutions I found here and on GitHub, but I could not make any of them work. The solutions I tried were these:
StackOverflow 1 (Meteor Issue 644): Are "group by" aggregation queries possible in Meteor, yet?
GitHub Arunoda's Approach: https://github.com/arunoda/meteor-smart-collections/issues/47
Also, I've tried to use the list-grouper (atmosphere package), but was not able to implement the package's instructions in my code.
If any good soul here knows how to do this, I would greatly appreciate it. Very, very much! :)
I did not find a 'submittedDate' property on the meteor document object. It may be necessary that when you insert a new document (entry) to your DB, that you specify current date/time as one of the parameters to go along with the rest.
There's more code there than's needed for dealing with your core question, I think. I've simplified a bit -- hopefully this helps. I'll just note I'm not an expert -- also learning. I haven't had time to test this. But I think it addresses a way of accomplishing what you need.
I think the basic structure of the template would look something like this.
<ul>
{{#each post}}
{{if isNewDate}}
<ul>
<li>{{writeDate}}</li>
</ul>
{{/if}}
<li>{{postName}}</li>
{{/each}}
</ul>
The helpers.js file could look something like this, I think.
var tempDate = {}; //we need a variable outside the scope of the helper functions
Template.foobar.helpers ({
post: function(){
Posts.find({}, {sort: {submittedDate: -1}});
},
isNewDate: function(){
//test if the date of this record matches the date of the previous record
//if it's new, return true.
//see momentJS -- makes dealing with dates sooooo much easier
if( moment().format("LL", this.submittedDate) !== moment().format("LL", tempDate)){
tempDate = this.submittedDate;
return true;
} else {
return false;
}
},
writeDate: function(){
return moment().format("LL", this.timestamp);
}
})

Categories

Resources