Meteor search clear results - meteor

I would like to make Meteor clear the last query, it does not accumulate my research. If I search in the input "Nº Património" and then doir again in the "Código Informática", I want to clear the first query results. What is happening is that it brings together the first and the second query results. Summing up, i want to se query results independently.Meteor search page
Template
<tbody>
<tr>
<th>Nº Património</th>
<th>Equipamento</th>
<th>Utilizador</th>
<th>Nº Helpdesk</th>
<th>Data Aquisição</th>
<th>Data Saída</th>
<th>Ultima Alteração</th>
</tr>
{{#each pesquisaEquipamentos}}
<tr>
<td>
{{npatrimonio}}
</td>
<td>
{{equipamento}}
</td>
<td>
{{utilizadores}}
</td>
<td>
{{helpdesk}}
</td>
<td>
{{daquisicao}}
</td>
<td>
{{dsaida}}
</td>
<td>
{{createdAt}}
</td>
</tr>
{{/each}}
</tbody>
Helper
if (Meteor.isClient) {
Template.pesquisar.helpers({
pesquisaEquipamentos: function() {
return Equipamentos.find();
}
});
Template.pesquisar.events({
"keypress input": function(event, template) {
if (event.keyCode == 13) {
var search = {};
search.value = event.target.value
search.name = event.target.name
//console.log(search.name, search.value);
Meteor.subscribe("pesquisaEquipamentos", search);
event.target.value = '';
}
}
});
}
Publication
Meteor.publish("pesquisaEquipamentos", function(search) {
//console.log(search.name);
//console.log(search.value);
switch (search.name) {
case 'npatrimonio':
return Equipamentos.find({
npatrimonio: search.value
});
break;
case 'cinformatica':
return Equipamentos.find({
cinformatica: search.value
});
break;
default:
}
});

Try stopping the subscription before you call it again:
var mySub;
Template.pesquisar.events({
"keypress input": function(event, template) {
if (event.keyCode == 13) {
var search = {};
search.value = event.target.value
search.name = event.target.name
if ( mySub ) mySub.stop(); // if you've previously subscribed clear those results
mySub = Meteor.subscribe("pesquisaEquipamentos", search);
event.target.value = '';
}
}
});

Related

Rocket Chat Filter changes with result set

I am updating the rocket chat app to have a departments filter on the department list page. I am running into an issue where my filter seems to be tied to the same collection as the result set. So when I update the filter all the other filter options are removed. I'm not sure the best way to make it so the filter only impacts the result list and not both.
Before:
After:
HTML
<template name="livechatDepartments">
{{#requiresPermission 'view-livechat-manager'}}
<fieldset>
<form class="form-inline" method="post">
<div class="form-group">
<label for="department">{{_ "Department"}}</label>
<select name="department">
<option value=""></option>
{{#each departmentsDDL}}
<option value="{{_id}}">{{name}}</option>
{{/each}}
</select>
</div>
<div class="form-group">
<label for="agent">{{_ "Served_By"}}</label>
<select name="agent">
<option value=""></option>
{{#each agents}}
<option value="{{_id}}">{{username}}</option>
{{/each}}
</select>
</div>
<button class="button">{{_ "Filter"}}</button>
</form>
</fieldset>
<div class="list">
<table>
<thead>
<tr>
<th width="20%">{{_ "Name"}}</th>
<th width="30%">{{_ "Description"}}</th>
<th width="10%">{{_ "Num_Agents"}}</th>
<th width="10%">{{_ "Num_Available_Agents"}}</th>
<th width="20%">{{_ "Enabled"}}</th>
<th width="20%">{{_ "Show_on_registration_page"}}</th>
<th>{{_ "Delete"}}</th>
</tr>
</thead>
<tbody>
{{#each departments}}
<tr class="department-info row-link" data-id="{{_id}}">
<td>{{name}}</td>
<td>{{description}}</td>
<td>{{numAgents}}</td>
<!--<td>{{}}</td>-->
<td>{{#if enabled}}{{_ "Yes"}}{{else}}{{_ "No"}}{{/if}}</td>
<td>{{#if showOnRegistration}}{{_ "Yes"}}{{else}}{{_ "No"}}{{/if}}</td>
<td><i class="icon-trash"></i></td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<div class="text-center">
<button class="button load-more">{{_ "Load_more"}}</button>
</div>
{{_ "New_Department"}}
{{/requiresPermission}}
JS:
Template.livechatDepartments.helpers({
departmentsDDL() {
return LivechatDepartment.find({}, { sort: { name: -1 } });
},
departments() {
return LivechatDepartment.find({}, { sort: { name: -1 } });
},
agents() {
return AgentUsers.find({}, { sort: { name: 1 } });
}
});
Template.livechatDepartments.events({
'click .remove-department' (e /*, instance*/ ) {
e.preventDefault();
e.stopPropagation();
swal({
title: t('Are_you_sure'),
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: t('Yes'),
cancelButtonText: t('Cancel'),
closeOnConfirm: false,
html: false
}, () => {
Meteor.call('livechat:removeDepartment', this._id, function(error /*, result*/ ) {
if (error) { return handleError(error); }
swal({
title: t('Removed'),
text: t('Department_removed'),
type: 'success',
timer: 1000,
showConfirmButton: false
});
});
});
},
'click .department-info' (e /*, instance*/ ) {
e.preventDefault();
FlowRouter.go('livechat-department-edit', { _id: this._id });
},
'submit form' (e, instance) {
e.preventDefault();
const filter = {};
$(':input', event.currentTarget)
.each(function() {
if (this.name) {
filter[this.name] = $(this)
.val();
}
});
instance.filter.set(filter);
instance.limit.set(20);
}
});
Template.livechatDepartments.onCreated(function() {
this.limit = new ReactiveVar(20);
this.filter = new ReactiveVar({});
this.subscribe('livechat:agents');
this.autorun(() => {
this.subscribe('livechat:departments', this.filter.get(), 0, this.limit.get());
});
});
Meteor Method:
Meteor.publish("livechat:departments", function(filter = {}, offset = 0, limit = 20) {
if (!this.userId) {
return this.error(
new Meteor.Error("error-not-authorized", "Not authorized", {
publish: "livechat:agents"
})
);
}
if (!RocketChat.authz.hasPermission(this.userId, "view-l-room")) {
return this.error(
new Meteor.Error("error-not-authorized", "Not authorized", {
publish: "livechat:agents"
})
);
}
check(filter, {
agent: Match.Maybe(String), // agent _id who is serving
department: Match.Maybe(String)
});
const query = {};
if (filter.agent) {
const DepartmentFilter = [];
RocketChat.models.LivechatDepartmentAgents
.find({
agentId: filter.agent
})
.forEach(department => {
DepartmentFilter.push(department);
});
var depts = DepartmentFilter.map(function(dep) {
return dep.departmentId;
});
As you stated in the question, your filter is tied to the same collection as your results set. So, how can you fix this?
Solution 1 - Easy, and if data in livechat:departments collection is not too large, probably the best:
Revert back your subscription code to fetch all data (not filtered), and filter in the departments helper function
// in Template.livechatDepartments.onCreated
this.subscribe('livechat:departments');
// in Template.livechatDepartments.helpers
departments() {
const departmentFilter = Template.instance().filter.get().department;
if (departmentFilter){
return LivechatDepartment.find({name: departmentFilter }, { sort: { name: -1 } });
}
else {
return LivechatDepartment.find({}, { sort: { name: -1 } });
}
}
Solution 2 - Keep departments helper with filter from Solution 1 ,
but now subscribe twice to livechat:departments
You can reuse the current publish for the filtered list of departments (add back your filtered subscription), and create a new pub/sub channel that publishes all the departments, but only needs to send the name + _id fields used to populate select options.

Using Handlebars for conditional CSS

In the snippet below I'd expect row a to have the class new-entry and row c to have the class moving-up but neither does.
I'm certain this is a silly mistake but I can't see it
Handlebars.registerHelper("newEntry", function() {
return this.newEntry ? 'class="new-entry"' : '';
});
Handlebars.registerHelper("movingUp", function() {
return this.movingUp ? 'class="moving-up"' : '';
});
var source = document.getElementById('leaderboard-template').innerHTML;
var template = Handlebars.compile(source);
var outlet = document.getElementById('outlet');
outlet.innerHTML = template({leaders: [
{name: 'a', signature_count: 10, newEntry: true},
{name: 'b', signature_count: 8},
{name: 'c', signature_count: 6, movingUp: false},
]});
.new-entry {
background-color:red;
}
.moving-up {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script>
<script id="leaderboard-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Constituency</th>
<th>Votes</th>
</thead>
<tbody>
{{#leaders}}
<tr {{newEntry}}>
<td>{{name}}</td>
<td><span {{movingUp}}>{{signature_count}}</span></td>
</tr>
{{/leaders}}
</tbody>
</table>
</script>
<div id="outlet"></div>
Handlebar converts the return value of a helper to an HTML escaped string. Use Handlebars.SafeString like this if you don't want that:
Handlebars.registerHelper("newEntry", function() {
return new Handlebars.SafeString( this.newEntry ? 'class="new-entry"' : '' );
});
Handlebars.registerHelper("movingUp", function() {
return new Handlebars.SafeString( this.movingUp ? 'class="moving-up"' : '' );
});

MeteorJS, Flow Router - Uncaught TypeError: pathDef.replace is not a function

I'm getting Uncaught TypeError: pathDef.replace is not a function console error using Flow Router in MeteorJS. I'm new to Flow having used Iron Router before so probably not doing something correctly.
Note that it works fine if I load another page first and then navigate to this page but I get the error if I reload the page.
Below is the faulty code:
Client template
{{#if Template.subscriptionsReady}}
{{#each users}}
<tr>
<td>
{{linkNames profile.firstname profile.lastname}}
</td>
<td>
{{username}}
</td>
<td>
{{emails.[0].address}}
</td>
<td>
{{toUpperCase roles.[0]}}
</td>
<td>
{{getUsernameById createdBy}}
</td>
<td>
<i class="fa fa-edit"></i>
</td>
<td>
<i class="fa fa-times"></i>
</td>
</tr>
{{else}}
<tr>
<td colspan="6">
<p>There are no users</p>
</td>
</tr>
{{/each}}
{{else}}
<p>Loading...</p>
{{/if}}
Pub
/* Users */
Meteor.publish('users', function() {
if (Roles.userIsInRole(this.userId, ['admin', 'team'])) {
return Meteor.users.find({}, {
fields: {
'profile.firstname': 1,
'profile.lastname': 1,
'emails': 1,
'username': 1,
'roles': 1,
'createdBy': 1
},
sort: {'roles': 1}
})
} else if (Roles.userIsInRole(this.userId, ['client'])) {
return Meteor.users.find({}, {
fields: {
'profile.firstname': 1,
'profile.lastname': 1,
'emails': 1,
'username': 1
}
});
}
});
Client JS
/* On created */
Template.users.onCreated(function() {
var instance = this;
instance.autorun(function() {
instance.users = function() {
instance.subscribe(Meteor.users.find({}));
}
});
});
/* Helpers */
Template.users.helpers({
users: function() {
var users = Meteor.users.find({});
return users;
}
});
I also get an error Exception in template helper: TypeError: Cannot read property 'username' of undefined in other templates for the following global helper (although the helper works as expected):
/* Current Username */
Template.registerHelper('currentUsername', function() {
return Meteor.user().username;
});
Your first error is probably happening due to an error in your routing code. Make sure you've defined the parameters in the route and are using them in any routing code correctly.
The second error is because Meteor.user() is not guaranteed to always be defined immediately. Change your helper to:
Template.registerHelper('currentUsername', function() {
var user = Meteor.user()
if( user ) {
return username;
}
});

How to fetch data from parse.com and render it to table using AngularJs

I am trying to fetch data stored in parse.com collection. I am using Parse Javascript SDK to call the service asynchronously as following:
ctrl.factory('TLDs', function($q){
var query = new Parse.Query(Fahras)// Fahras is the Parse Object initialized earlier in code
query.equalTo("type", "Domain")
var myCollection = query.collection()
return {
fetchDomains: function(){
var defer = $q.defer();
myCollection.fetch({
success : function(results) {
defer.resolve(results.modles);
console.info(results.models)
},
error : function(aError) {
defer.reject(aError);
}
});
console.info(defer.promise)
return defer.promise;
}
}
}) // end of factory topDomains
I have a simple table to show the fetched data
<div id="showdomainshere"> {{domains}}</div>
<table id="domains_table" class="table table-hover">
<thead>
<tr>
<th>Domain</th>
<th>Code</th>
<th>Subjects</th>
<th>Instances</th>
</tr>
</thead>
<tbody id="table_body">
<form id="edit_row" class="form-inline">
<tr ng-repeat="item in domains">
<td><span>{{item.attributes.arTitle}}</span>
</td>
<td><span>{{item.attributes.domainCode}}</span>
</td>
<td><span>{{subclasses}}</span>
</td>
<td><span>{{instances}}</span>
</td>
</tr>
</form>
</tbody>
</table>
</div> <!-- end of main div -->
And hereunder the controller I ma using to render the view:
ctrl.controller('Home', ['$scope','TLDs',function($scope, TLDs) {
$scope.domains = TLDs.fetchDomains()
}])
Using console.info I can see that the result is fetched and I can go through the array of returned models as expected. Problem is that $scope.domains never been updated and as a result the table never been rendered
Fortunately I am able to figure it out.
The controller should be like:
ctrl.controller('Home', ['$scope','TLDs',function($scope, TLDs) {
TLDs.fetchDomains().then(function(data){
$scope.domains = data
})
}
While the factory itself should be like:
ctrl.factory('TLDs', function($q){
var query = new Parse.Query(Fahras)
query.equalTo("type", "Domain")
var myCollection = query.collection()
return {
fetchDomains: function(){
var defer = $q.defer();
myCollection.fetch({
success : function(results) {
defer.resolve(results.models)
return results.models
},
error : function(aError) {
defer.reject(aError)
}
})
return defer.promise;
}
} }) // end of factory

Table sorting causing duplication in meteor

In my meteor app I have a table of data with sorting for each coloumn. When I keep on clicking the coloumn for sorting, the table itself is getting multiplied.
This is the code for setting session variables.
'click #coloumn_name' : function()
{
var oldOrder = Session.get("sortOrder");
var sortField = 'coloumn1';
Session.set("sortField",sortField );
if(oldOrder == 1)
{
var newOrder = -1;
Session.set("sortOrder",newOrder );
}
else
{
var newOrder = 1;
Session.set("sortOrder",newOrder );
}
}
Here is the code for reading the session variables and fetching data from db.
Template.templatename.vname = function()
{
var filter = {sort: {}};
var sortField = Session.get('sortField');
var sortOrder = Session.get('sortOrder');
if(!sortField)
{
sortField = 'coloumn2';
}
if(!sortOrder)
{
sortOrder = 1;
}
filter.sort[sortField] = sortOrder;
return Groups.find({}, filter);
}
Here is my template
<template name="templatename">
<table>
<tr>
<th>Group Name</th>
<th>Status</th>
</tr>
{{#each vname }}
<tr>
<td> {{name}} </td>
<td> {{status}} </td>
</tr>
{{/each}}
</table>
</template>
This is the table before trying to sort.
This is the image after trying to sort
Does anyone have any idea why this happens ?

Resources