javascript - sharing settings/config between client and backend -
i have application using node.js backend , require.js/backbone frontend. backend has config/settings system, depending on environment (dev, production, beta) can different things. propagate of variables client well, , have them affect template rendering (e.x change title or url of pages).
what best way achieve that?
i came way it, , seems working don't think smartest thing , can't figure out how make work requirejs optimizer anyway. on backend expose /api/config method (through get) , on client have following module config.js:
// module loads environment config // server through api define(function(require) { var cfg = require('text!/api/config'); return $.parsejson(cfg); });
any page/module needs config do:
var cfg = require('config');
as said having problem approach, can't compile/optimize client code requirejs optimizer since /api/config file doesn't exist in offline during optimization. , sure there many other reason approach bad idea.
i following (note jade, have never used require.js or backbone, long can pass variables express templating language, should able place json in data-*
attributes on element want.)
// app.js app.get('/', function(req, res){ var bar = { a: "b", c: math.floor(math.random()*5), }; res.locals.foo = json.stringify(bar); res.render('some-jade-template'); }); // some-jade-template.jade !!! html head script(type="text/javascript" , src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") script(type="text/javascript") $.ready(init); function init(){ var json = $('body').attr('data-stackoverflowquestion'); var obj = json.parse(json); console.log(obj); }; body(data-stackoverflowquestion=locals.foo) h4 passing data data-* attributes example
Comments
Post a Comment