meteor template helpers function not working properly - meteor

I have 2 functions in Template.meetings.helpers, but only one function is working.
Template.meetings.helpers({
group: function() {
console.log('meeting id from helper group = ' + this.meetingId);
console.log('group id from helper group = ' + this.groupId);
return Groups.findOne({_id: this.groupId});
},
meeting: function() {
console.log('meeting id from helper meeting = ' + this.meetingId);
console.log('group id from helper meeting = ' + this.groupId);
return Meetings.findOne({_id: this.meetingId});
},
});
My console shows the following:
router.js:73 meetingId from router = ZKkLLvdCpRmrF7uXD
router.js:74 groupId from router = xFSzAHBEps2dSKcWM
meetings.js:26 meeting id from helper meeting = ZKkLLvdCpRmrF7uXD
meetings.js:27 group id from helper meeting = xFSzAHBEps2dSKcWM
router.js:
Router.route('/meetings/:_id/:groupId?', {
waitOn: function() {
return Meteor.subscribe('meeting');
return Meteor.subscribe('Group');
},
action: function () {
console.log('meetingId from router = ' + this.params._id);
console.log('groupId from router = ' + this.params.groupId);
this.render('meetings', {
data: {
meetingId: this.params._id,
groupId: this.params.groupId
}
});
},
onBeforeAction: function(){
var currentGroup = Members.find({
groupId: this.params.groupId,
memberId: Meteor.userId()
}).count();
Session.set('groupId', this.params.groupId);
var currentUser = Meteor.userId();
if(currentUser && currentGroup > 0){
this.next();
} else {
this.render("landingPage");
}
}
});
I can't figure out why the group: function() is not outputting to the console.
Any suggestions?

Related

How to avoid ISPOSTBACK in an asp.net jquery(ajax) application?

I have an ASP.NET WEB API application using jquery/Ajax. When I select "M1" in my dropdownlist a gridview shows data for Machine 1, when I click "update" button. If change to "M2", the gridview show data for M1 AND M2. It continue to add data. I only want to see data for M1 or M2 and so on. The problem is probadly due to POSTBACK function. How to solve this? Update panel?
function update() {
$.ajax({
type: 'GET',
url: '/api/stop/',
dataType: "JSON",
data: "data",
success: function (data) {
$.each(data, function (i, data) {
if (data.machinename == $("#DropDownList11").val() && data.name != $(null).val() && data.overlimit == 1 && data.stopcause ==$(null).val())
{
var _id = data.id;
var _machinename = data.machinename;
var _stopcause = data.stopcause;
var _machinename = data.machinename;
var _name = data.name;
var _stop1 = data.idlestart;
var _stop2 = data.idlestop;
var _data = '<tr><td>' + _id + ' </td><td>' + _machinename + '</td><td>' + _name + '</td><td>' + _stop1 + '</td><td>' + _stop2 + '</td><td>';
var _data2 = '<option>' + data.id + '</option>'
$('table').append(_data);
$('#DropDownList5').append($(_data2))
};
});
}
});
}
Well, My Guess is, the problem is in your append logic, $('table').append(_data);. You keep on appending your data to the table and not clearing the previous ones. Just try to clear the data before going in the $.each api of jQuery. Something like below:
$.ajax({
type: 'GET',
url: '/api/stop/',
dataType: "JSON",
data: "data",
success: function (data) {
$("table tr").remove(); // this line will clear off the previous table tr elements before appending new ones.
$.each(data, function (i, data) {
if (data.machinename == $("#DropDownList11").val() && data.name != $(null).val() && data.overlimit == 1 && data.stopcause ==$(null).val())
{
var _id = data.id;
var _machinename = data.machinename;
var _stopcause = data.stopcause;
var _machinename = data.machinename;
var _name = data.name;
var _stop1 = data.idlestart;
var _stop2 = data.idlestop;
var _data = '<tr><td>' + _id + ' </td><td>' + _machinename + '</td><td>' + _name + '</td><td>' + _stop1 + '</td><td>' + _stop2 + '</td><td>';
var _data2 = '<option>' + data.id + '</option>'
$('table').append(_data);
$('#DropDownList5').append($(_data2))
};
});
}
});
Moreover, I am not sure where is the POSTBACK function that you are mentioning, as best of my knowledge, POSTBACK functions are part of WebForms and not WebAPIs. So, I assume you by POSTBACK method you meant the method success.

how do I replace the text "rows" in pagination

In the pagination example, how do I replace the text at the bottom, "rows" with another word e.g. "products"?
Showing 1 to 10 of 800 rows
becomes
Showing 1 to 10 of 800 products
Ported from issue # 882 on bootstrap-table's issue tracker.
This text is part of bootstrap-table's localizations. English (en-US) is loaded by default.
Solution # 1
Create and include a custom locale
/js/locale/bootstrap-table-en-US-custom.js
(function ($) {
'use strict';
$.fn.bootstrapTable.locales['en-US-custom'] = {
formatLoadingMessage: function () {
return 'Hold your horses...';
},
formatRecordsPerPage: function (pageNumber) {
return pageNumber + ' bananas per page';
},
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return 'Showing ' + pageFrom + ' to ' + pageTo + ' of ' + totalRows + ' products';
},
formatSearch: function () {
return 'Search';
},
formatNoMatches: function () {
return 'No matching records found';
},
formatPaginationSwitch: function () {
return 'Hide/Show pagination';
},
formatRefresh: function () {
return 'Refresh';
},
formatToggle: function () {
return 'Toggle';
},
formatColumns: function () {
return 'Columns';
},
formatAllRows: function () {
return 'All';
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US-custom']);
})(jQuery);
It is also important to note, that the localization settings get merged in to the table settings -meaning that you can simply
Solution # 2 Pass them as an argument in your table settings:
$('#table').bootstrapTable({
// .. your other table settings
pagination: true,
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return 'Showing ' + pageFrom + ' to ' + pageTo + ' of ' + totalRows + ' rows';
}
});
or you can
var $table = $('#bootstrap-table');
$table.bootstrapTable({
toolbar: ".toolbar",
clickToSelect: true,
showRefresh: true,
search: true,
showToggle: true,
showColumns: true,
pagination: true,
searchAlign: 'left',
pageSize: 8,
clickToSelect: false,
pageList: [8,10,25,50,100],
formatRecordsPerPage: function(pageNumber){
return pageNumber + " rows visible";
},
formatShowingRows: function(pageFrom, pageTo, totalRows){
//do nothing here, we don't want to show the text "showing x of y from..."
return 'Showing ' + pageFrom + ' to ' + pageTo + ' of ' + totalRows + ' ';
}
});
based on jtrumbull`s totally correct answer, I would spent a third one:
Solution # 3 use a locale and merge / overwrite parts of them with your own:
in this example, we will overwrite the already defined "formatShowingRows" function.
// create an array where you store your own translations
var mylocale = {
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return 'Ergebnisse <b>' + pageFrom + '-' + pageTo + '</b> von <b>' + totalRows + '</b>';
}
}
// extend the used locale
$.extend(true, $.fn.bootstrapTable.locales.de, mylocale);

Asp.net webform with flot.js chart on return Json does not work

I am using ASP.NET webforms for flot charts I connected to database in test.aspx.cs file using [Webmethod] where I can return json.
I stored the return value both in textarea and $.plot(placeholder, [and also here], options) It does not print the graph in placeholder however when I do:
var data = past
the value of textarea here and run applicationn it prints to me the value.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetLocation(string location)
{
List<string> result = new List<string>();
StringBuilder strQuery = new StringBuilder();
strQuery.Append("SELECT Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica) AS SDay, COUNT(Statistiche.ID_Tabella) AS Stats");
strQuery.Append(" FROM Statistiche INNER JOIN Tabelle ON Statistiche.ID_Tabella = Tabelle.ID_Tabella INNER JOIN");
strQuery.Append(" Location ON Statistiche.ID_Colonna_Statistica = Location.ID_Location");
strQuery.Append(" WHERE (Statistiche.ID_Tabella = 2) AND (Statistiche.ID_Box = 60) AND (Location.Nome_Location = 'Albilò')");
strQuery.Append("GROUP BY Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica)");
string query = strQuery.ToString();
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int counter = 1;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (counter == 1)
{
result.Add("[{'label': 'Europe (EU27)','data':[[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
}
else
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
if (counter==31)
{
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]]}]");
}
counter++;
}
return result;
}
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test.aspx/GetLocation",
data: "{'location':'Albilò'}",
success: function drawChart(msg) {
var options = { lines: { show: true }, points: { show: true }, xaxis: { tickDecimals: 0, tickSize: 1} };
var ddata = [];
var data = msg.d;
for (var i = 0; i < 32; i++) {
ddata.push(data[i]);
}
var placeholder = $("#placeholder");
$("#txtvalue").val(ddata);
var datad = $("#txtvalue").text();
$.plot(placeholder, ddata, options);
},
error: function () {
alert("call is called111");
}
});
First of all, why do you create JSON yourself? You've already specified to return JSON in you attributes.
Refactore method to return simple array of POCO objects like
[Serializable]
public class pocoObject
{
public string Label;
..
}
Then your method should just return list of object and have attributes set up:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<pocoObject> GetLocation(string location)
{
...
return result; // result is list of pocoObjects
}
Flot.js is rather sensitive to data you set as source, so after this take a look at data in firebug, it should be correct json formatted data. So please visit wiki and also compare your data to working samples.
This how you can initiliaze legend names of you plot:
$(function () {
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d1.push([i, Math.sin(i)]);
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d2.push([i, Math.cos(i)]);
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.1)
d3.push([i, Math.tan(i)]);
$.plot($("#placeholder"), [
{ label: "sin(x)", data: d1},
{ label: "cos(x)", data: d2},
{ label: "tan(x)", data: d3}
], {
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]
},
yaxis: {
ticks: 10,
min: -2,
max: 2
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] }
}
});
});

web grid server pagination trigger multiple controller call when changing page

When I server-filter on "au" my web grid and change page, multiple call to the controller are done :
the first with 0 filtering,
the second with "a" filtering,
the third with "au" filtering.
My table load huge data so the first call is longer than others.
I see the grid displaying firstly the third call result, then the second, and finally the first call (this order correspond to the response time of my controller due to filter parameter)
Why are all that controller call made ?
Can't just my controller be called once with my total filter "au" ?
What should I do ?
Here is my grid :
$("#" + gridId).kendoGrid({
selectable: "row",
pageable: true,
filterable:true,
scrollable : true,
//scrollable: {
// virtual: true //false // Bug : Génère un affichage multiple...
//},
navigatable: true,
groupable: true,
sortable: {
mode: "multiple", // enables multi-column sorting
allowUnsort: true
},
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
serverGrouping:false, // Ne fonctionne pas...
pageSize: '#ViewBag.Pagination',
transport: {
read: {
url: Procvalue + "/LOV",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8"
},
parameterMap: function (options, type) {
// Mise à jour du format d'envoi des paramètres
// pour qu'ils puissent être correctement interprétés côté serveur.
// Construction du paramètre sort :
if (options.sort != null) {
var sort = options.sort;
var sort2 = "";
for (i = 0; i < sort.length; i++) {
sort2 = sort2 + sort[i].field + '-' + sort[i].dir + '~';
}
options.sort = sort2;
}
if (options.group != null) {
var group = options.group;
var group2 = "";
for (i = 0; i < group.length; i++) {
group2 = group2 + group[i].field + '-' + group[i].dir + '~';
}
options.group = group2;
}
if (options.filter != null) {
var filter = options.filter.filters;
var filter2 = "";
for (i = 0; i < filter.length; i++) {
// Vérification si type colonne == string.
// Parcours des colonnes pour trouver celle qui a le même nom de champ.
var type = "";
for (j = 0 ; j < colonnes.length ; j++) {
if (colonnes[j].champ == filter[i].field) {
type = colonnes[j].type;
break;
}
}
if (filter2.length == 0) {
if (type == "string") { // Avec '' autour de la valeur.
filter2 = filter2 + filter[i].field + '~' + filter[i].operator + "~'" + filter[i].value + "'";
} else { // Sans '' autour de la valeur.
filter2 = filter2 + filter[i].field + '~' + filter[i].operator + "~" + filter[i].value;
}
} else {
if (type == "string") { // Avec '' autour de la valeur.
filter2 = filter2 + '~' + options.filter.logic + '~' + filter[i].field + '~' + filter[i].operator + "~'" + filter[i].value + "'";
}else{
filter2 = filter2 + '~' + options.filter.logic + '~' + filter[i].field + '~' + filter[i].operator + "~" + filter[i].value;
}
}
}
options.filter = filter2;
}
var json = JSON.stringify(options);
return json;
}
},
schema: {
data: function (data) {
return eval(data.data.Data);
},
total: function (data) {
return eval(data.data.Total);
}
},
filter: {
logic: "or",
filters:filtre(valeur)
}
},
columns: getColonnes(colonnes)
});
Here is my controller :
[HttpPost]
public ActionResult LOV([DataSourceRequest] DataSourceRequest request)
{
return Json(CProduitsManager.GetProduits().ToDataSourceResult(request));
}
The 3 correspond to the initial load (no filtering) and the following ones as you type in the condition of filter, similar in kendoAutocomplete but in kendoAutocomplete there are a couple of options (time and min length) that control when to send the requests (I couldn't find anything similar in grid).
If your problem is loading a huge amount of data I do recommend limiting the size of the data transmitted using pageSize in the DataSource definition. But, obviously, this is not a solution if what takes long is executing the query.
In such scenarios it is recommended to create a typing delay and thus perform a request when the user has stopped typing (unless he is typing slower than regular typing).
To create a delay I can suggest you the following:
<script type="text/javascript">
var globalTimeout = null;
$('#searchInput').keyup(function () {
if (globalTimeout != null) clearTimeout(globalTimeout);
globalTimeout = setTimeout(SearchFunc, 500);
});
function SearchFunc(){
globalTimeout = null;
$('#yourGridName').data('kendoGrid').dataSource.filter({ field:"theField",operator:"startswith",value:$('#searchInput').val() })
}
</script>

MVC Datetime picker validation

I have an MVC application.My page contain two date time picker.start date and end date.My requirement is,
when anyone select the start date ,the end date should be calculated as start date +10 days.
also one condition, end date should not be less than start date.
How can i possible?
$(document).ready(function ()
{
$("#txtstartdate").datepicker
({
dateFormat: 'mm/dd/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
}
});
$("#txtEnddate").datepicker
({
dateFormat: 'mm/dd/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
}
});
});
I am using jquery datetime picker.
I just used javascript code but when I select the datetime picker it always showing prevoius selected date.how can I get selected date on selecting the datetime picker?
Try this:
$(function ()
{
$('#txtStartDate, #txtEndDate').datepicker(
{
showOn: "both",
beforeShow: customRange,
dateFormat: 'mm/dd/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
},
firstDay: 1,
changeFirstDay: false
});
});
function customRange(input)
{
var min = new Date(2008, 11 - 1, 1); //the absolute minimum date
var dateMin = min;
var dateMax = null;
var dayRange = 10; //range of days
if (input.id == "txtStartDate")
{
if ($("#txtEndDate").datepicker("getDate") != null)
{
dateMax = $("#txtEndDate").datepicker("getDate");
dateMin = $("#txtEndDate").datepicker("getDate");
dateMin.setDate(dateMin.getDate() - dayRange);
if (dateMin < min)
{
dateMin = min;
}
}
else
{
dateMax = new Date(); //the absolute maximum date
}
}
else if (input.id == "txtEndDate")
{
dateMax = new Date(); //the absolute maximum date
if ($("#txtStartDate").datepicker("getDate") != null)
{
dateMin = $("#txtStartDate").datepicker("getDate");
var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(), dateMin.getDate() + dayRange);
if(rangeMax < dateMax)
{
dateMax = rangeMax;
}
}
}
return {
minDate: dateMin,
maxDate: dateMax,
};
}​
DEMO: http://jsfiddle.net/XdFpg/

Resources