Meteor, display/sort value by boolean - javascript

I'm working on a table in Meteor template, where the is a boolean field "emergency"
I would like to display in the table the cells where there is the "emergency" flag FIRST, and then the others ...
How can I do that please ?
here is the find, I tried to sort(), find and sort inside but It doesn't work .. :/
Template.actionsList.helpers({
actions: function() {
return Actions.find();
}
});
Thanks in advance :)
I get the error: Exception in template helper: TypeError: Cannot read property 'hasOwnProperty' of null
My code is:
Session.set('emergency', false);
Template.actionForm.onRendered(function () {
var $elem = this.$('.emergency');
$elem.checkbox('set ' + (Session.get('emergency') ? 'checked' : 'unchecked'));
$elem.checkbox({
onChange: function () {
Session.set('emergency', !Session.get('emergency'));
}
});
});
Template.actionForm.events({
'submit .new-action': function(event) {
event.preventDefault();
var emergency = Session.get('emergency');
...
Actions.insert({
emergency: emergency
....
Thanks for the help

Use underscore's sortBy() method to sort on objects checking if the 'emergency' field exists via the hasOwnProperty() native method:
Template.actionsList.helpers({
actions: function() {
var actions = Actions.find().fetch();
return _.sortBy(actions, function (a) { return !a.hasOwnProperty('emergency'); });
}
});
Check the demo below.
var actions = [
{
"_id" : "ukn9MLo3hRYEpCCty",
"field" : "foo"
},
{
"_id" : "ukn9MLo3hRYEpCCty",
"field" : "bar",
"emergency": true
},
{
"_id" : "WMHWxeymY4ATWLXjz",
"field" : "abc",
"emergency": false
},
{
"_id" : "5SXRXraariyhRQACe",
"field" : "xyz"
}
];
var result = _.sortBy(actions, function (a) { return !a.hasOwnProperty('emergency'); });
pre.innerHTML = JSON.stringify(result, undefined, 4);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<pre id="pre"></pre>

Related

Accessing a variable in vuejs or javascript

I have this javascript variable, I'm using vuejs.
when I try to access an array field to validate a form, the chrome dev tools returns an error.
var checkItems = {contact_email: "", contact_name: "", contact_phone: "", message: "", subject_id: null, …}
I try to access this way:
if(checkItems.contact_email)
alert("email required");
This is the error:
Property or method "contact_email" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option
If the form fields are empty, I want to detect individually which one is empty and send a custom error for each one, for example:
Name field is empty
The email field is empty
This is my vuejs code:
var locale = '{{ $lang }}'; //'es-ES',
var V_Alerts = new Vue({
el : '#v-alerts',
data : {
types : ['danger', 'warning', 'success', 'info'],
alerts : [
]
},
methods : {
add : function(type, content, opts)
{
this.alerts.push({
type : type,
content : content,
opts : opts
});
},
addSuccess : function(content, opts){
this.add('success',content, opts)
}
}
});
var new_ticket = new Vue({
el : '#create_ticket',
data : {
uploading : false,
submitting : false,
subject_id : null,
message : '',
errors: [],
},
methods : {
validation: function (params)
{
return {
contact_email : IsEmail(params.contact_email),
contact_name : !!params.contact_name.trim(),
message : !!params.message.trim(),
subject_id : params.subject_id && !!params.subject_id.trim(),
captcha : params.captcha !== 0
}
},
isValid : function(params)
{
var validation = this.validation(params);
return Object.keys(validation).every(function (key) {
return validation[key];
});
},
restart : function()
{
this.uploading = false;
this.submitting = false;
this.subject_id = null;
this.$refs.subjects.restart();
this.$refs.uploads.restart();
$('#message').text('');
$('#order_number').val('');
$('#contact_email').val('');
$('#contact_name').val('');
$('#contact_phone').val('');
$('#message').val('');
grecaptcha.reset();
},
onSubjectSelect : function(subject_id){
this.subject_id = subject_id;
},
_onSubjectsLoaded : function(subjects){
emitOnWidgetContentChanged();
},
createTicket : function(e)
{
var params = {
contact_email : $('#contact_email').val(),
contact_name : $('#contact_name').val(),
contact_phone : $('#contact_phone').val(),
message : $('#message').val(),
subject_id : this.subject_id,
message_files : this.$refs.uploads.completed_ids.join(','),
captcha : grecaptcha.getResponse()
};
#if (Input::has('public_token'))
params.public_token = '{{ Input::get('public_token') }}';
#endif
if ($('#order_number').val() != '')
params.contact_orders = $('#order_number').val();
if (!this.isValid(params))
{
var checkItems = params;
if(checkItems.contact_email)
alert("email");
alert('{{ addslashes(trans('common.empty_or_error_input')) }}');
return;
}
this.submitting = true;
// only ie11 need this manuall
params._token = '{!! csrf_token() !!}';
AjaxServices.post('createTicket', params, function(error, result)
{
this.submitting = false;
if (error)
{
alert('{{ addslashes(trans('accounts/tickets.error_creating_ticket')) }}');
grecaptcha.reset();
}
else
{
alert('#'+ result.ticket_id +' - {{ addslashes(trans('accounts/tickets.new_ticket_created_ok')) }} :)');
V_Alerts.addSuccess('#'+ result.ticket_id +' - {{ addslashes(trans('accounts/tickets.new_ticket_created_ok')) }}');
this.restart();
emitOnWidgetContentChanged();
}
}.bind(this));
},
onUploadComplete : function(ids){
this.uploading = false;
emitOnWidgetContentChanged();
},
onUploadStarted : function(){
this.uploading = true;
setTimeout(emitOnWidgetContentChanged,1);
},
onItemDeleted : function(){
},
onFilesSelected : function(){
}
}
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$(document).ready(function(){
//new_ticket.restart();
});
You are not utilizing Vue properly. The error you are receiving stems from not defining your properties in the data object. You cant just return them as you are in the validation method because Vue is looking for a data object called contact_email, or a method called contact_email() or even a computed property called contact_email.
data : {
// define your properties here
contact_email: '';
},
methods: {
yourMethod: function(){
//modify your properties here
this.contact_email: IsEmail(params.contact_email)
}
}

Need to Format this JSON properly and display in HTML using AJAX

I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,
It's the first time I see a JSON like this.
I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.
I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...
I'm using scheb/yahoo-finance-api on packagist for that, if it helps.
Thanks for your help.
{
query: {
count: 1,
created: "2017-06-07T12:34:44Z",
lang: "en-US",
results: {
quote: {
symbol: "APLL",
Symbol: "APLL",
LastTradePriceOnly: "0.119",
LastTradeDate: "6/6/2017",
LastTradeTime: "11:13am",
Change: "+0.023",
Open: "0.119",
DaysHigh: "0.119",
DaysLow: "0.110",
Volume: "300"
}
}
}
}
$(function(){
$("#get-data").click(function() {
//do ajax here and load data
var showData = $('#show-data');
var $data = $.getJSON("data.php", function(data) {
// $data = $data.responseText;
function buildTree(data, container) {
$data.forEach(function(node) {
var el = document.createElement(node.tag);
if (Array.isArray(node.content)) {
buildTree(node.content, el);
}
else if (typeof(node.content) == 'object') {
buildTree([node.content], el);
}
else {
el.innerHTML = node.content;
}
container.appendChild(el);
});
}
console.log($data);
buildTree($data, document.body);
});
});
});
That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)
literal notation, not Json.
You can go over this in a for in loop, something like this:
var x = {
query: {
count: 1,
created: "2017-06-07T12:34:44Z",
lang: "en-US",
results: {
quote: {
symbol: "APLL",
Symbol: "APLL",
LastTradePriceOnly: "0.119",
LastTradeDate: "6/6/2017",
LastTradeTime: "11:13am",
Change: "+0.023",
Open: "0.119",
DaysHigh: "0.119",
DaysLow: "0.110",
Volume: "300"
}
}
}
}
for (var key in x) {
if (!x.hasOwnProperty(key)) continue;
var obj = x[key];
for (var prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
alert(prop + " = " + obj[prop]);
}
}
Is this what you want to achieve?
// let's assume this is your data
var data = {
query: {
count: 1,
created: "2017-06-07T12:34:44Z",
lang: "en-US",
results: {
quote: {
symbol: "APLL",
Symbol: "APLL",
LastTradePriceOnly: "0.119",
LastTradeDate: "6/6/2017",
LastTradeTime: "11:13am",
Change: "+0.023",
Open: "0.119",
DaysHigh: "0.119",
DaysLow: "0.110",
Volume: "300"
}
}
}
};
// prints one li with key and value
function printTree(key, value, container) {
var li = $('<li></li>');
if (typeof value === 'object') {
// value is a nested object, create a new <ul> element for it
li.append(key + ': ');
var ul = $('<ul></ul>');
for (var index in value) {
printTree(index, value[index], ul); // call the function recursively
}
li.append(ul);
} else {
li.text(key + ': ' + value);
}
container.append(li);
}
printTree('data', data, $('#container')); // call the function for the first time
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="container">
This is in literal notation so I assume you've already parsed it into an object. Let's call that object myObject
var myObject={
query : {
count : 1 ,
created : "2017-06-07T12:34:44Z" ,
lang : "en-US" ,
results : {
quote : {
symbol : "APLL" , Symbol : "APLL" , LastTradePriceOnly : "0.119" , LastTradeDate : "6/6/2017" , LastTradeTime : "11:13am" , Change : "+0.023" , Open : "0.119" , DaysHigh : "0.119" , DaysLow : "0.110" , Volume : "300" } } } }
You can access properties as follows:
var myCount = myObject.query.count
console.log(myCount) // logs 1

Firebase Rule for Data Validation

Assuming a data structure like below, I want a rule that disallows adding new car makes, for example users cannot add "toyota". So, I need to .validate such that the .update must match an existing make.
I have tried using $cars with ".validate": "newData.val().contains($cars)" and all kind of other ways with no luck. Any help is appreciated.
My code is:
function setModel(model,make,key){
if (model && make && key){
var carsRef = ref.child('cars');
var makeRef = carsRef.child(make);
var modelRef = makeRef.child(model);
var obj = {};
obj[key] = true;
modelRef.update(obj, onComplete);
}
}
The firebase looks like:
{
"cars" : {
"chevrolet" : {
"silverado" : {
"id192874623" : true,
"id786766663" : true
}
},
"ford" : {
"taurus" : {
"id736273627" : true
}
},
"honda" : {
"accord" : {
"id635263535" : true
}
}
}}
To disallow adding new car brands:
"cars": {
"$brand": {
".validate": "data.exists()"
}
}
This is covered in the section on existing data vs new data of the documentation.

Set values to the folded defaults in Backbone.Model

I have an object inside defaults like this:
app.MultiwidgetModel = Backbone.Model.extend({
defaults : {
....
operatorData : {
helloBlock : null,
greeting : null,
avatarBlock : null,
avatarImg : null
},
....
},
initialize: function(){
....
}
});
How can I set values to the operatorData inner properties (helloBlock, greeting) etc in the initialize function? If it is possible, what syntax should I use?
If you just want to set values to the current model in initialize and trigger the approriate change events, this should work:
app.MultiwidgetModel = Backbone.Model.extend({
defaults : {
....
operatorData : {
helloBlock : null,
greeting : null,
avatarBlock : null,
avatarImg : null
},
....
},
initialize: function(){
var opData = this.get('operatorData');
opData.helloBlock = 'foo';
opData.greeting = 'bar';
...
this.set({operatorData: opData}); // Without this, the data will change but you won't have a change:operatorData event triggered
}
});
If you want to edit the default values you should be able to use
app.MultiwidgetModel.prototype.defaults.operatorData = {
helloBlock : 'foo',
greeting : 'bar'
}
Is that what you want?

How do I loop JSON data returned by jquery? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I return JSON and loop through the returned json in jQuery in MVC app?
This is my data returned by MVC controller and I get this in my success callback:
[{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "First comment!!", "dt" : { "$date" : 1304966277978 } },
{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Second comment!!", "dt" : { "$date" : 1304966347677 } },
{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Third comment!!", "dt" : { "$date" : 1304966493240 } }
]
Controller:
[HttpGet]
public JsonResult GetComments(params...)
{
return Json(new { comments = GetFromDB().ToJson() }, JsonRequestBehavior.AllowGet);
}
Problem:
I tried several ways to loop the rows. But all seems infinite loop.
$.ajax(
{
type: "GET",
url: "/comment/GetComments",
dataType: "json",
data: "app=" + app + "&eid=" + eid + "&pg=" + pg + "&pgs=" + pgs,
success: function (result) {
$.each(result[comments], function () {
$.each(this, function (k, v) {
alert('this a column or attribute');
});
alert('end of row');
});
},
error: function (req, status, error) {
alert('Error=' + error + ' & Status=' + status);
}
});
Also tried:
$.each(result["comments"], function (key, value) {
alert('comment found');
});
How can I loop the rows & access each attribute's value?
You could just use a simple for loop:
for (var i = 0, len = results.length; i < len; i++) {
// do something with results[i].text
}
See example →
EDIT: If you need to first convert a JSON string to a Javascript object then before the loop you should:
results = JSON.parse(results);
$.getJSON("YourControllerHere.XXX",{}, function(data){
$.each(data, function(key, val) {
$('#someLocation').append('<li>' + val.text + '</li>'); //This is just an example. You can do something with each row/ value pair here.
});
});
You should be able to step through the rows and values with this.
Best,
T
This is a duplicate from another post today - that you posted? : )
How do I return JSON and loop through the returned json in jQuery in MVC app?
Your first problem is that there is no result["comments"] field in your JSON. You're getting an array back, of what I assume is the comments themselves. So you need to iterate on that. Something like
$.each(result, function(k, v) { console.log(v.user); });
should work, I just tried it in the browser. The following code iterates through the rows, and then iterates through the attributes of each row:
$.each(foo, function(k, row) { $.each(row, function(attr, value) { console.log(attr, value); }) });
for(var key in json)
for(var key in (obj = json[key]))
{
//obj holds the current object in the json array
console.log(obj[key]);
}

Categories