Tuesday, 15 July 2014

node.js - Sharing JavaScript model code between server and client, is this approach valid? -



node.js - Sharing JavaScript model code between server and client, is this approach valid? -

i'm origin learning node.js , backbone. i'd share code between server , client (related [1] , [2]). more in deep:

share defaults values model. defaults used populate forms (client-side), while enforced server-side share validation rules in order dry , perform client/server validation share instance methods

so thought utilize factory object encapsulate mutual code (defaults, validation rules, public instance methods) , adapt factory object based on environment (node.js or amd module).

this code quick&dirty , may not work. approach or waste of time?

class="lang-js prettyprint-override">(function (factory) { if (typeof exports === 'object') { // node.js var config = require('../config/config.json'), sequelize = require('sequelize'), _ = require('underscore'); var user = { receivesms: { type: sequelize.boolean, allownull: false }, receivenewsletter: { type: sequelize.boolean, allownull: false } }; // add together defaultvalue each returned _.each(factory.defaults, function (value, key) { if(_.has(user, key)) { user[key].defaultvalue = value; } }); module.exports = function () { (new sequelize(config.database, config.username, config.password)) .define('user', user); }; } else if (typeof define === 'function' && define.amd) { // amd define(['backbone', 'uderscore'], function (backbone, _) { homecoming backbone.model.extend(factory); }); } }(function () { homecoming { // adapted defaults: { receivesms: false, receivenewsletter: true } } }));

i think it's improve solution utilize require.js (especially using frameworks underscore in multiple files). should utilize mill objects alter during runtime. shopping cart illustration (but in illustration think it's more appropriate utilize backbone collection given function argument when instantiated). see more info here: http://requirejs.org/docs/node.html

javascript node.js backbone.js requirejs amd

No comments:

Post a Comment