Meteor helper functions versus variables? - javascript

I was trying to display a count of all online users on my website, and installed the meteor-user-status plugin to help with this. I thought all I had to do was add a template helper
Template.header.helpers({
numOnline: Meteor.users.find({"status.online":true}).count()
});
like so, and include the {{numOnline}} variable in my header template. But, for some reason, that resulted in always displaying 0 users online. However, when I simply ran the method Meteor.users.find({"status.online":true}).count() in the javascript console, it gave the correct amount of users online.
After messing around with it a bit, I got it to work by wrapping it in a function:
Template.header.helpers({
numOnline: function(){
return Meteor.users.find({"status.online":true}).count();
}
});
This change makes it work perfectly, but I have no clue why. Can someone explain why it was necessary to wrap it in a function?

Adding Christian Fritz, The only reason I think this can be happening is in the first case numOnline: Meteor.users.find({"status.online":true}).count() the collection is not ready at the point of evaluation of the template and assign 0 or empty array [] since is what the subscription return, and in the second case since is a function will react whenever a change occurs in a collection, so that's why will have the value a soon the collection get fill with the subscription and the function will get execute whit the most recent value.Just my two cents. Please correct me if I'm wrong.

Well, that's just what it is (and the documentation tells you so, too). The reason why this need to be a function is reactivity: in order to reevaluate the piece of code at a later point in time (when a reactive datasource has changed value), you need to have a function.

Related

can't access array of objects in object

I'm baffled about why I'm getting an error when trying to access an array inside of an object in ReactJS.
I am using Redux to store an object in State.
I have a success function that allows the page to render, so by the time I get to this object it has for sure loaded. (I noticed a ton of similar questions to this where that's usually the problem).
When I do this I get the proper results:
const { events } = this.props
console.log(JSON.stringify(events.listSignup))
{"data":[{"eventID":"264712106049274377","name":"BookOne","email":null,"verify":null,"privacy":null,"order":null,"group":null},{"eventID":"264712106049274377","name":"BookTwo","email":null,"verify":null,"privacy":null,"order":null,"group":null}]}
I can see that the array "data" exists, but when I try:
console.log(JSON.stringify(events.listSignup.data[0].name))
or
console.log(JSON.stringify(events.listSignup.data[0]))
I get "TypeError: Cannot read property 'data' of undefined"
I'm at my wits end trying to figure out what's going on. Any advice would be much appreciated!
You're right to be baffled, because what you [think you] have observed isn't possible.
This happens a lot to me as a developer, and my advice is that when this happens, trust your knowledge (you know this isn't possible!) and double check what you are seeing.
I suspect that the first time your component renders, this.props.events is undefined, but then it very quickly re-renders with this.props.events being set.
I would suggest adding back this line (without the others):
console.log(JSON.stringify(events.listSignup))
And scrolling up in your javascript console to see if you have any logs that are just displaying undefined. If so, you probably need to double check the logic which is preventing the page from rendering before you have successfully received the data, as I suspect that is where your problem is.

Make properties lazy

I was reading the article on best practices here. And i came across the following lines:
A developer might attempt to set a property on your element before its definition has been loaded. This is especially true if the developer is using a framework which handles loading components, inserting them into to the page, and binding their properties to a model.
And the proposed solution to solve this problem was:
_upgradeProperty(prop) {
if (this.hasOwnProperty(prop)) {
let value = this[prop];
delete this[prop];
this[prop] = value;
}
}
I have been trying the understand the scenario in which this would happens, and try to understand how this fragment of code solves this problem. I have trying to find any reference material around but wasnt able to find anything similar like this.
Please could someone explain this scenario and what problem are we trying to solve here.
Web Components doesn't fully initialize your element until you call customElements.define('custom-tag', CustomElement); however, any <custom-tag> exists in the DOM as an HTMLUnknownElement as soon as the page renders. So in the period of time between when the page renders and when you call customElements.define(...), it's possible for someone to call something like:
document.querySelector('custom-tag').someProperty = someValue
which would modify the property of the not-yet initialized CustomElement.
Why would this happen?
I think this would most likely come up as a side-effect of using Web Components with a frontend framework (Angular, Vue, etc). These frameworks often have initialization code that happens after render, and there may be situations where a user may not have sufficient control to prevent the framework from initializing before Web Components.
How does the code fragment solve the problem?
The fragment function, _upgradeProperty() is meant to be called within the connectedCallback(), which is called after the Web Component has been fully defined and attached to an existing element. If you have any custom setter in your class, like:
class CustomElement {
set someProperty(value) {
this._someProperty = value.toLowerCase();
}
}
Then it's possible the property was set before the setter existed, meaning the raw value was saved directly to the instance's someProperty property, instead of being converted to lowercase and saved to _someProperty. Deleting the property and reassigning it after the setter has been defined ensures that the value is properly processed (in this case, made lowercase and saved in the right location).

Struts2 how to get an ActionError count in a jsp

In Struts2 I have successfully implemented an updateErrorCount() method that updates a class member variable every time addActionError() is called through out various action classes. I can then access that variable with a property tag in the associated jsp. However, I am looking for a better solution.
Since the s:actionerror tag lists all of the errors added, is there a way to use an iterator tag or some other solution to display the error count along with all of the error messages right in the jsp?
I thought about overriding addActionError() to avoid having to call an additional method to keep an error count but if I could simply do it all in the jsp it seems much cleaner.
getActionErrors returns a collection, why can't you just call size on that?
I see few legitimate reasons to implement any of this functionality manually.
If you have specific needs you should enumerate them in your question, otherwise I don't see the point of doing this on your own.

Ext JS - How to Grok the Syntax

I needed to figure out how to get the value of a field on my form from within a handler function but I didn't know how to reference the field and kept getting errors. I spent time looking at the API, code examples and googling. Finally I found one example which works (I imagine there are others).
Assuming a form named MyForm and a field 'myField'
var myVal = myForm.getForm().findField("myField").getValue();
Maybe I'm just too new at this, but I don't think it's obvious from looking at the API docs.
So my question is, when you're trying to figure something out, what's your approach.
Thanks!
Assuming you have set the id of the field, you can use Ext.getCmp(id) to have the ComponentManager look it up. There's also Ext.getDom(id) which basically acts as a wrapper to getElementById.
In addition, many event handler functions allow setting the scope of the function itself. The documentation for that event should note which object is setting the scope. You may be able to set the form field as the scope object and use this.getValue() but it's hard to say without knowing exactly what you're trying to do.
To answer the question at hand: the more you code, the more you grok. Ext JS has a bit of a learning curve but the example source code provided in the download is a great place to start. There are several errors and omissions in the documentation though, so the most authoritative place to go for answers is straight into the source. Reading up on JavaScript callbacks doesn't hurt either.

JavaScript - Advisability of closing and returning state in a single method

My team is debating the right name for a UI framework JavaScript method that ultimately does the following:
It gets the widgets state, if any
It removes the widget from the page
It returns the retrieved state so that the framework can recreate it
later
The initially proposed name was 'destroy.' Some team members feel that people may not expect a method named destroy to return anything. The name 'getStateAndDestroy' is more descriptive but suggests a single responsbility principle failure.
Thoughts? Do you see this as more of a naming or design issue?
git has something very similar, with the name stash.
What about 'stow'?
Makes me think of packing it away for possible later use.
Sounds like the element/widget is being cloned and removed, to be re-created at a later point, in the process.
What about: cloneAndRemove or backupAndDestroy hmmm they're pretty similar to what you've already got though.
How about 'takeAway' or 'takeOut' or 'grab'. Also reminds me a bit of the 'pop' method on a stack. I also think 'remove' is suitable for returning what you removed.

Categories