I was wondering whether there is a way to pass variables from templates to template helper functions.
I've got a few nesting loops but no way of knowing which data i'm looping.
Thanks in advance
Yes (http://docs.meteor.com/#/full/template_helpers):
Helpers can accept positional and keyword arguments:
Template.myTemplate.helpers({
displayName: function (firstName, lastName, keyword) {
var prefix = keyword.hash.title ? keyword.hash.title + " " : "";
return prefix + firstName + " " + lastName; } });
Then you can call this helper from template like this:
{{displayName "John" "Doe" title="President"}}
If beyond that you would like to use data from the template's current data context as argument to the helpers, you can do that, too, of course. For example, if the current data context includes firstname, lastname and title:
{{displayName firstname lastname title=title}}
This is handy in an #each loop, for instance. And if you don't know what's in your current context, then just use console.log(this) inside the helper function and you'll see the complete data context on your console.
Related
I have a string of sequence say "aby,abraham,issac,rebecca,job,david,daniel" now I need to add space after the comma.
I bind the value using ng-bind and display the result using ng-show. I'm unable to use join as it is received as array from the database.
You can directly bind like this,
<span ng-bind="users.name.split(',').join(', ')" ng-show="users.name"></span>
No need to create filters.
To initialize the value, use ng-init directive to hardcode the value to Username
ng-init="Username='aby,abraham,issac,rebecca,job,david,daniel'"
You can use filter to do this task
.filter('commaSpace', [function () {
return function (str) {
return str.replace(',/g', ', ');
};
}])
I'm using a third party package that defines a schema like this:
People.schema = new SimpleSchema({
firstName: {
type: String,
optional: false
}
//Many other fields defined...
});
I would like to modify it to have optional: true for the first name without changing the source code for the third party package.
I could use People.schema.pick to get a schema with all of the fields except the firstName, and then combine this with another schema with firstName as optional. But this method would require listing all of the fields in the schema in the pick function, which is tedious.
Is there a better way of accomplishing this?
I can edit the object simple schema creates just like any other object:
People.schema._schema.firstName.optional = true.
To override the field.
Thanks my poor English skill, I have o express my idea by these code below..
Friendly edit:
I am trying to write a generalized confirmAndRemoveCollection method which takes in the collectionName and itemId, and I would like to perform operations on this collection. Since collectionName is a string, I wouldn't be able to perform DB operations on it. Could someone please suggest how I could use the collection name to get access to the actual collection object.
confirmAndRemoveCollection:(collectionName,itemId)->
check(itemId,String)
check(collectionName,String)
sweetAlert({
title:"confirm"
text:"blabla"
type:"info"
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "delete"
cancelButtonText: "cancel"
closeOnConfirm: false,
},(isConfirm)->
if isConfirm
collectionName.remove(itemId)
else
return
swal(
'success'
"selected item deleted"
"success"
)
The variable collectionName is a string object, so you won't be able to call MongoDB methods on it.
One way to accomplish your task is to create an object that maps the string name to the collection object.
For example:
Posts = new Mongo.Collection('posts');
Comments = new Mongo.Collection('comments');
Collections = {
'Posts': Posts,
'Comments': Comments
};
Then you could do something like this in your code
if isConfirm
Collections[collectionName].remove(itemId)
Just to add an alternative here (even though the question is really old): you can pass the collection itself as an argument and it will work.
As the collection is an Object, when you pass it as an argument it will be passed "by reference" and you will be able to call its methods.
Following the example by #FullStack (which also works, of course):
Posts = new Mongo.Collection('posts');
Comments = new Mongo.Collection('comments');
const collectionRemove = (collection, id) => {
const count = collection.remove(id);
console.log(`Removed ${count} items with id ${id} from collection ${collection._name}`)
}
And then do something like:
collectionRemove(Posts, 1);
collectionRemove(Comments, 24);
I've got a user control which lets users provided their own script names that are called by the control on specific events.
I have the following code:
initialize : function()
{
// Call the base initialize method
Point74.WebAutoComplete.callBaseMethod(this, 'initialize');
$(document).ready(
Function.createDelegate(this, this._onDocumentReady)
);
},
_onDocumentReady : function()
{
var me = this;
$("#" + me.get_id()).autocomplete(me.get_ashxAddress(),
{
formatItem: function(item)
{
return eval(me.get_formatFunction() + "(" + item + ");");
}
}
).result(me.get_selectFunction());
}
me.get_formatFunction contains the name of a function, i.e. "FormatItem". This example is currently using eval, which I do not want to use... plus this example doesn't work anyway, but I thought I'd show what I'm trying to get at.
In the example above, I get a value undefined error as 'item' is a string array and eval tries to convert it into one long string.
How can I achieve this functionality any still pass through 'item' as a string array to the named function?
If passing named functions is a bad idea, are there any alternatives?
This is how my control is declared:
<p74:WebAutoComplete runat="server" ID="ato_Test" AshxAddress="WebServices/SearchService.ashx"
FormatFunction="formatItem" SelectFunction="searchSelectedMaster" />
me[me.get_formatFunction()](item);
If your intent is to pass all arguments to the user-specified function that are passed to formatItem(), then instead of using:
formatItem: function(item)
{
return eval(me.get_formatFunction() + "(" + item + ");");
}
Use:
formatItem: function()
{
return me.get_formatFunction().apply(me, arguments));
}
The apply() method can be called on a function object, in order to invoke that function using the specified "this" and argument array. See: http://odetocode.com/blogs/scott/archive/2007/07/04/function-apply-and-function-call-in-javascript.aspx for an explanation of the call() and apply() functions in javascript.
Then you will want get_formatFunction() to return a function object, rather than just the name of the function; or you can try:
me[me.get_formatFunction()]
...to get a function which is defined on 'me' by its name. (Note that if get_formatFunction() returns the string 'myFunc', then this is equivalent to me.myFunc)
[Edit: changed references to 'this' to use 'me' instead]
I'm not sure what your overall plan is, but you can pass functions around themselves instead of their names:
function Foo(x, y) {
// do something
}
function Bar(f, a, b) {
// call Foo(a,b)
f(a,b);
}
Bar(Foo, 1, 2);
I have a web service that returns me a JSON object that contains the string "Hello World". How do I pull this string out of the object?
data = [object Object]
Thanks
Nick
You have to know how is your object, what members the object have.
You could try something like
for(var e in data)
alert(e + ' : ' + data[e]);
You can either use eval:
var foo = eval('(' + data + ')');
But that is potentially dangerous, especially if you don't trust what is being sent from the server. Thus, the best way (and most secure way) to extract data from a JSON object is by using Crockford's JSON library:
var foo = JSON.parse(data);
Btw, if you're using jQuery to query ASP.Net Web Services, be careful of the the d. issue (which is used as a container object). Thus to extract the returned object, you have to do:
var foo = JSON.parse(data);
if (foo) {
//Foo is not null
foo = f.d;
}
More information about this here: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
If you are using jQuery's post function you might follow this example found here.
$.post("test.php", { func: "getNameAndTime" },
function (data) {
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
In your case, I would suspect that you would call data.data.