Reputation: 4250
While I can pass an object's data, I don't know how to pass/call an object's functions.
route.js:
router.get('/', function(req, res, next) {
let test = {}; // passing an object called test
test.hello = function() { //the test object has a method I want to
console.log('hello'); //call on the browser
}
res.render('home.jade', { test:test });
On the .jade page:
//- let test = !{test}; //renders as [object Object]
let test = !{JSON.stringify(test, null, 4)}; //renders empty obj
test.hello();
console.log('test', test);
Console message:
Uncaught TypeError: test.hello is not a function
Rendered source file:
//- let test = [object Object];
let test = {};
test.hello();
console.log('test', test);
An example of what works on my.jade file (what I don't want):
let test = {};
test.hello = #{test.hello};
test.hello();
This will console out 'hello'. However, I imagine that there is a way to pass and call an object's function without this workaround.
Thanks for any help.
Upvotes: 1
Views: 971
Reputation: 968
JSON.stringify
will strip away functions since JSON format does not support functions/methods. From MDN:
Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like Date will be a string after JSON.parse().
Technically you can use eval
to evaluate the resulting string to a function, though this is not recommended.
Upvotes: 1