How to show content of collection to other users? - javascript

At first I am a beginner in meteor. I am creating an app for school. Users can add something to a collection. My problem is that only the author sees the task at the moment. How can i fix it?
Edit: My js code
if (Meteor.isClient)
{
Template.Collection.onCreated(function() {
var self = this;
self.autorun(function() {
self.subscribe('tasks');
});
});
Template.Collection.helpers({
tasks: ()=> {
return tasks.find({inCollection: true});
}
});
Template.Tasks.onCreated(function() {
var self = this;
self.autorun(function() {
self.subscribe('tasks');
});
});
Template.tasks.helpers({
tasks: ()=> {
return tasks.find({});
}
});
Template.Tasks.events({
'click .new-task': () => {
Session.set('newTask', true);
}
});
Template.TaskSingle.onCreated(function() {
var self = this;
self.autorun(function() {
var id = FlowRouter.getParam('id');
self.subscribe('singleTask', id);
});
});
Template.TaskSingle.helpers({
task: ()=> {
var id = FlowRouter.getParam('id');
return Tasks.findOne({_id: id});
}
});
Template.NewTask.events({
'click .fa-close' : function() {
Session.set('newTask', false);
}
});
Template.Task.onCreated(function(){
this.editMode = new ReactiveVar(false);
// this.editMode = new ReactiveVar();
//this.editMode.set(false);
});
Template.Task.helpers({
updateTaskId: function() {
return this._id;
},
editMode: function() {
return Template.instance().editMode.get();
}
});
Template.Task.events({
'click .toggle-menu': function() {
Meteor.call('toggleMenuItem', this._id, this.inCollection);
},
'click .fa-trash' : function() {
Meteor.call('deleteTask', this._id);
},
'click .fa-pencil' : function(event, template) {
template.editMode.set(!template.editMode.get());
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
//code to run on server at startup
});
Meteor.publish('tasks', function(){
return tasks.find({author: this.userId});
});
Meteor.publish('singleTask', function(id){
check(id, String);
return Tasks.find({_id: id});
});
// Configure Accounts to require username instead of email
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
}

If you've removed the autopublish package then documents then you need to create publications and subscriptions for documents to be sent to clients.
On the server you write: Meteor.publish('items', function () { return Items.find(); }.
And on the client you would subscribe with Meteor.subscribe('items');.

You clearly publish the tasks for the author only:
Meteor.publish('tasks', function(){
return Tasks.find({author: this.userId});
});
If you want it to be visible to everyone, it should be
Meteor.publish('tasks', function(){
return Tasks.find();
});

Related

How to stop a timeout if it is running in javascript

I have a timeout setup like this below:
var someObj = {
init: function() {
someObj.timeout();
someObj.someWork();
},
timeout : setTimeout(function() {
someObj.myFunc();
}, 15000),
myFunc: function() {
console.log('myFunction called');
},
someWork: function(){
console.log('some work');
if(this.timeout !== null){
console.log('clearing timeout...');
clearTimeout(this.timeout);
}
}
}
$(function() {
someObj.init();
});
I want to stop the timeout if it is assigned to timeout variable and not null.
Jsfiddle link: https://jsfiddle.net/jy2p7jtd/17/
Is it possible?
Update:
Is this valid way to assign a timeout and clear it?
var someObj = {
timeout :null,
init: function() {
someObj.make();
someObj.someWork();
},
make: function(){
this.timeout = setTimeout(function() {
console.log('myFunction called');
}, 15000)
},
someWork: function(){
console.log('timeout is ', this.timeout);
if(this.timeout !== null){
console.log('clearing timeout...');
clearTimeout(this.timeout);
}
}
}
$(function() {
someObj.init();
});
updated link: https://jsfiddle.net/jy2p7jtd/41/
declare another property timeoutId:null and check if it is present then clear it.
var someObj = {
timeoutId: null,
init: function() {
this.timeoutId = this.timeout();
someObj.someWork();
},
timeout: function() {
return setTimeout(function() {
someObj.myFunc();
}, 15000)
},
myFunc: function() {
console.log('myFunction called');
},
someWork: function() {
console.log('some work');
if (this.timeoutId) {
console.log('clearing timeout...');
clearTimeout(this.timeoutId);
}
}
}
$(function() {
someObj.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
clearTimeout() prevents the function set with the setTimeout() to execute.

Displaying all users in Meteor

I have a template that I am trying to display all users in called userList.
//server
Meteor.publish("userList", function() {
var user = Meteor.users.findOne({
_id: this.userId
});
if (Roles.userIsInRole(user, ["admin"])) {
return Meteor.users.find({}, {
fields: {
profile_name: 1,
emails: 1,
roles: 1
}
});
}
this.stop();
return;
});
Thanks in advance for the help!
if you want show all the user you can try in your publish.js file:
Meteor.publish('userList', function (){
return Meteor.users.find({});
});
in your router you susbcribe to this
Router.route('/users', {
name: 'usersTemplate',
waitOn: function() {
return Meteor.subscribe('userList');
},
data: function() {
return Meteor.users.find({});
}
});
The next step is iterate your data in the template.
if you don't want subscribe in the router, you can subscribe in template level, please read this article for more details.
https://www.discovermeteor.com/blog/template-level-subscriptions/
Regards.
This should work!
// in server
Meteor.publish("userList", function () {
return Meteor.users.find({}, {fields: {emails: 1, profile: 1}});
});
// in client
Meteor.subscribe("userList");
This should work.
subscribe(client)
publish(server)
Client:
UserListCtrl = RouterController.extend({
template: 'UserList',
subscriptions: function () {
return Meteor.subscribe('users.list', { summary: true });
},
data: function () {
return Meteor.users.find({});
}
});
Server:
Meteor.publish('users.list', function (options) {
check(arguments, Match.Any);
var criteria = {}, projection= {};
if(options.summary){
_.extend(projection, {fields: {emails: 1, profile: 1}});
}
return Meteor.users.find(criteria, projection);
});

Issues searching backbone collection

I have this bb app that I'm trying to search and return the results of the search, then when cleared, so all results again. I was able to get everything to show before adding the search feature, but now nothing showing up. I think the collection isn't available at the time it's trying to populate, but can't seem to get it to wait. I've tried moving the fetch around to no avail. Any help would be greatly appreciate. For the sake of ease, I've put everything in a fiddle that can be found here...
//Campaign Model w defaults
app.model.Campaign = Backbone.Model.extend({
default: {
title: '',
img: '',
id: '',
slug: '',
image_types: 'small',
tagline: ''
}
});
//Campaign Collection from model
app.collection.Campaign = Backbone.Collection.extend({
//our URL we're fetching from
url: 'https://api.indiegogo.com/1/campaigns.json?api_token=e377270bf1e9121da34cb6dff0e8af52a03296766a8e955c19f62f593651b346',
parse: function(response) {
console.log('parsing...');
return response.response; //get array from obj to add to collection based on model
},
currentStatus: function(status){
return _(this.filter(function(data){
console.log('currentStats', status);
return data.get('_pending') == status;
}));
},
search: function(searchVal) {
console.log('search...');
if (searchVal == '') {
return this;
}
var pattern = new RegExp(searchVal, 'gi');
return _(this.filter(function(data) {
return pattern.test(data.get('title'));
}));
}
});
app.collection.campaigns = new app.collection.Campaign();
app.collection.campaigns.fetch({
success: function(){
console.log('Success...');
var sHeight = window.screen.availHeight - 200 + 'px';
$('#container ul').css('height', sHeight);
},
error: function() {
console.log('error ',arguments);
}
});
//List view for all the campaigns
app.view.CampaignList = Backbone.View.extend({
events: {
'keyup #searchBox': 'search'
},
render: function(data) {
console.log('campaignList',$(this.el).html(this.template));
$(this.el).html(this.template);
return this;
},
renderAll: function(campaigns) {
console.log('campList renderAll', campaigns, $('#campaignList'));
$('#campaignList').html('');
campaigns.each(function(campaign){
var view = new app.view.CampaignItem({
model: campaign,
collection: this.collection
});
console.log(view);
$('#campaignList').append(view.render().el);
});
return this;
},
initialize: function() {
console.log('init campList',app);
this.template = _.template($('#campaignList-tmp').html());
this.collection.bind('reset', this.render, this);
},
search: function(e) {
console.log('listView search');
var searchVal = $('#searchBox').val();
this.renderAll(this.collection.search(searchVal));
},
sorts: function() {
var status = $('#campSorting').find('option:selected').val();
if(status == '') {
status = false;
};
this.renderAll(this.collection.currentStatus(status));
}
});
//Item view for single campaign
app.view.CampaignItem = Backbone.View.extend({
events: {},
render: function(data){
console.log('campItem render...', data);
this.$el.html(this.template(this.model.toJSON()));
return this;
},
initialize: function(){
console.log('campItem init');
this.template = _.template( $('#campaignItem-tmp').html());
}
});
//Router
app.router.Campaign = Backbone.Router.extend({
routes: {
'': 'campaigns'
},
campaigns: function(){
this.campListView = new app.view.CampaignList({
collection: app.collection.campaigns
});
$('#container').append(this.campListView.render().el);
this.campListView.sorts();
}
});
app.router.campaigns = new app.router.Campaign();
Backbone.history.start();
http://jsfiddle.net/skipzero/xqvrpyx8/

Backbone Fetching Process

I have Backbone Model that collect data from server:
Job.Models.Response = Backbone.Model.extend({
defaults: {
'authStatus': false,
'id': '1',
'name': 'name',
},
urlRoot: '/static/js/public/json/'
});
I have button with data-id = "id from /static/js/public/json/".
Job.Views.Response = Backbone.View.extend({
el: '.ra-response-button',
events: {
"click": "load"
},
load: function () {
var info = this.$el.data();
this.model.set({ id: info.id});
this.model.fetch();
if (this.model.attributes.authStatus === false) {
console.log('Register')
}
else {
console.log('Unregister')
}
}
});
If i console.log my model after fetch, its dont update, but data fetch success.
What kind of problem can be here?
Here i init our plugin:
var responseModel = new Job.Models.Response;
var response = new Job.Views.Response({ model: responseModel });
I resolve my problem. Finally View.
Job.Views.Response = Backbone.View.extend({
el: '.ra-response-button',
events: {
"click": "load"
},
load: function () {
var that = this;
var info = that.$el.data();
that.model.set({ id: info.id});
that.model.fetch({
success: function() {
if (that.model.attributes.authStatus === true) {
new Job.Views.ResponseForm({ model: that.model })
}
else {
new Job.Views.ResponseAuth({ model : that.model })
}
},
error: function() {
alert('Error, repeat please.')
}
});
}
});

Backbone Router Issue - Will not load specific action when accessed through the URL

Can someone look at the code below and let me know why when accessing domain.com/#issue/1 it shows the default action which is the list instead? but when clicking on of the click elements and the url changes to #issue/1 it actually works.
// Destroy Views
Backbone.View.prototype.close = function () {
console.log('Closing view ' + this);
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};
// Backbone Router
var AppRouter = Backbone.Router.extend({
initialize:function () {
$('#header').html(new HeaderView().render().el);
},
routes:{
"issue/add":"addIssue",
"issue/:id":"viewIssue",
"":"list",
},
list:function () {
this.before(function () {
console.log('test');
this.issueList = new IssueCollection();
this.issueListView = new IssueListView({model:this.issueList});
this.issueList.fetch();
app.showView('#content', new IssueListView({model:this.issueList}));
});
},
viewIssue:function (id) {
console.log(id, app.issueList);
this.before(function () {
var issue = app.issueList.get(id);
app.showView('#content', new IssueView({model:issue}));
});
},
addIssue:function () {
this.before(function () {
app.showView('#content', new IssueView({model:new Issue()}));
});
},
showView:function (selector, view) {
if (this.currentView)
this.currentView.close();
$(selector).html(view.render().el);
this.currentView = view;
return view;
},
before:function (callback) {
if (this.issueList) {
if (callback) callback();
} else {
this.issueList = new IssueCollection();
this.issueListView = new IssueListView({model:this.issueList});
this.issueList.fetch();
$('#content').html(this.issueListView.render().el);
}
}
});
tpl.loadTemplates(['header', 'issue-details', 'issue-item', 'issues-list'], function () {
app = new AppRouter();
Backbone.history.start();
});
Thanks.
I believe it has to do with the way you are loading the router with tpl.loadTemplates(). I've recreated the issue on jsfiddle and the problem goes away when you go to the show url:
http://jsfiddle.net/HXE7K/
Working Example:
http://jsfiddle.net/HXE7K/show/
http://jsfiddle.net/HXE7K/show/#issue/1
http://jsfiddle.net/HXE7K/show/#issue/add
Solved this by doing the following:
It appears that the tpl.loadTemplates had nothing to do with it but the way the .before function is being executed with the callback.
// Destroy Views
Backbone.View.prototype.close = function () {
console.log('Closing view ' + this);
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};
// Backbone Router
var AppRouter = Backbone.Router.extend({
initialize:function () {
$('#header').html(new HeaderView().render().el);
},
routes:{
"issue/add":"addIssue",
"issue/:id":"viewIssue",
"":"list",
},
list:function () {
console.log('List Route');
this.before(function () {
this.issueList = new IssueCollection();
this.issueListView = new IssueListView({model:this.issueList});
this.issueList.fetch();
app.showView('#content', new IssueListView({model:this.issueList}));
});
},
viewIssue:function (id) {
console.log('View Issue Route ' + id);
this.before(function () {
var issue = app.issueList.get(id);
app.showView('#content', new IssueView({model:issue}));
});
},
addIssue:function () {
console.log('Add Issue Route');
this.before(function () {
app.showView('#content', new IssueView({model:new Issue()}));
});
},
showView:function (selector, view) {
if (this.currentView)
this.currentView.close();
$(selector).html(view.render().el);
this.currentView = view;
return view;
},
before:function (callback) {
if(!this.issueList) {
this.issueList = new IssueCollection();
this.issueListView = new IssueListView({model:this.issueList});
this.issueList.fetch({
success: function(coll, resp) {
if(callback) {
callback();
}
}});
} else {
if(callback) {
callback();
}
}
}
});
tpl.loadTemplates(['header', 'issue-details', 'issue-item', 'issues-list'], function () {
app = new AppRouter();
Backbone.history.start();
});

Categories

Resources