Curious if I do it right, and if not the way you guys approach this.
I have a Jade template that should display some data retrieved from a MongoDB database, and I also need to have access to this data inside the client side JavaScript file.
I use Express.js and send the data to the Jade template as follows:
var myMongoDbObject = {name : 'stephen'}; res.render('home', { locals: { data : myMongoDbObject } });
Then inside home.jade I can do things like:
p Hello
What writes out:
Hello stephen!
Now what I want also has access to this data object inside the client-side JS file so that I can manipulate the object, say, by clicking a button before sending it back to the server to update the database.
I was able to accomplish this by storing the "data" object inside the hidden input field in the Jade template, and then extracting the value of this field inside my client-side JS file.
Inside home.jade
- local_data = JSON.stringify(data) // data coming in from Express.js input(type='hidden', value=local_data)
Then in my client side JS file, I can access local_data as follows:
Inside myLocalFile.js
var localObj = JSON.parse($("#myLocalDataObj").val()); console.log(localObj.name);
However, this difficult business / litigation feels dirty. I know that I can bind data object values ββto DOM objects in my Jade template and then retrieve these values ββusing jQuery, but I would like to have access to the actual object returned from Express in my JS client side.
Is my solution optimal, how would you guys do it?
braitsch Jun 06 '12 at 18:03 2012-06-06 18:03
source share