I am building a blog with Node.js, Express and MongoDB. In my "create new post" template I have a title field and a slug field.
I am using the Slugs for Node.js from NPM: https://npmjs.org/package/slugs
What I am trying to do is:
So I would type "My favorite character is &" in the title field and the value in the alias field would dynamically change to "my-favorite-character-is".
I believe you have to do something like the accepted answer in this question: JADE + EXPRESS: Iterating over object in inline JS code (client-side)?
However, that was more for referencing variables rather than executing functions. And it seems like that is preprocessed and then you can't access it anymore.
Is what I'm trying to do even possible?
Or should I go with something like this? https://github.com/stipsan/String.Slugify.js
Here's what I tried to no avail:
!= "<script>"
!= "var post_title = document.getElementById('title');"
!= "var post_alias = document.getElementById('alias');"
!=
!= "var aliasValidator = function() {"
!= " this.value = " + slug( + "this.value" ) + ";"
!= "};"
!= "var titleValidator = function() {"
!= " post_alias.value = " + slug( + "this.value" ) + ";"
!= "};"
!=
!= "post_title.addEventListener({'keyup': titleValidator, 'keydown': titleValidator, 'change': titleValidator});"
!= "post_alias.addEventListener({'change': aliasValidator});"
!= "</script>"
And here's the view where the variable is passed:
var slugs = require('slugs');
newPost: function(req, res) {
return res.render('add-post', {
title: "Write new post",
slug: slugs,
dayDateName: tools.dayName
});
}
This should be pieced together with a few things:
public/slugs.js file, as well as more sophisticated things like browserify or RequireJS. Start simple, but to directly answer your question, no, you can't just magically call a function that exists within your node process from the browser directly but YES you can share the same function in both node and the browser using one of the aforementioned techniques.For jade, you don't need all those crazy != prefixes, just do this (this has no direct bearing on your question, just FYI).
script
var put = "your raw javascript here";
var jade = "knows what to do and you don't need prefixes or escaping";
The way you are writing your template, you seem to be implying the function will be executed on the client.
This is not possible.
Instead, you should use an ajax call back to your server to execute the slug function, or precompute all the values and send this to the client.