React – a sweet new javascript ui library

Just had a short run-thru of the tutorial for the React library by Facebook/Instagram.

I’m really liking the declarative approach. It’s nice and clean.

Going thru the tutorial, things felt very straightforward, sensible and apparent.

And, the docs are great!

It claims “ultra-high performance” due to it’s virtual DOM diff implementation, which is very interesting for anyone who’s has run into performance issues when working with complex & large dataset client side applications.

Hopefully JSX syntax highlighting comes to Sublime Text soon.

I’m definitely keeping an eye on this project. It looks likely to become my preferred javascript UI framework in the near future.

React homepage or github

Advertisements

Node.js, express, mongoose.js and modules

I found node.js modules (exports) a little confusing at first.

So, here’s a small example using node.js with mongoose and modules to represent something closer to a real world project structure.

app.js references auctions.js which is basically the controller logic.

auctions.js references ./models/auction.js which holds the model and schema.

app.js

var express = require('express');
var mongoose = require('mongoose');

var app = module.exports = express.createServer();

mongoose.connect('mongodb://localhost/marketplace');

app.configure(function () {
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
});

app.get('/', function (req, res) {
    console.log('hi');
    res.send('hello world');
});

// auctions api
var auctions = require('./auctions.js');
app.get('/auctions', auctions.list);
app.post('/auctions/create', auctions.create);

app.listen(3000);

auctions.js

// load up the model
var Auction = require('./models/auction.js');

exports.create = function (req, res) {
    // replace data assigments with something like
    // {comments: req.body.comments}
    new Auction({
        iso_currency_symbol: 'GBP',
        comments: 'second auction'
    }).save();

    res.send('hello, this is response text');
}

exports.list = function (req, res) {
    Auction.find(function (err, auctions) {
        res.send(auctions);
    });
}

./models/auction.js

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var auction_schema = new Schema({
    iso_currency_symbol: String,
    created_date: { type: Date, default: Date.now },
    started_date: { type: Date },
    owner_id: ObjectId,
    comments: String
});

module.exports = mongoose.model('Auction', auction_schema);

Note: I’m not a node.js expert so if there is a better way to do this, lemme know 🙂

ASP.Net MVC3 ajax form loading that preserves unobtrusive validation AND has custom json validation

Well, this is a mouthful to describe.

Here’s an example concept I came up with during the early ASP.Net MVC 3 days.

I wanted to be able to use the unobtrusive client side model validation forms in a partial view but load them via jquery ajax calls.

In addition, I had some quite complex server side validation that needed to be done.
The catch? Those complex server side calls HAD to always be server side AND they should not cause the form to reload. So, Custom Validators didn’t seem to work the way I wanted (bear in mind that the information on on mvc3 was pretty light).

The form gets hijaxed to preserve the unobtrusive validation.
If the form’s model is invalid it returns the original form partial html.
If the form’s model is valid, we return a JsonResponseViewModel json object.
This object can have a status of “Ok” or “Error”.
If “Error”, then a list of JsonResponseErrors exists. We parse and display those on the client.
If “Ok” then just we are all good 🙂

There’s probably a better way to do this but I thought I should just share this with the world anyways.

The example solution:
ASP.Net MVC3 ajax based client side notification of server server side validation.
Also shows you how to load a standard MVC3 unobtrusive form via ajax and keep the MVC model validation for both server and client side.

Grab it here

node.js, expressjs and jsonp example

Here’s a quick and simple example on how to make a jsonp call to a node.js + express server

node.js + express code:

var express = require('express');

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/logget', function(req, res){
  console.log('get to log');
  console.log(req.query.callback);
  console.log(req.param('somedata'))
  
  res.header('Content-Type', 'application/json');
  res.header('Charset', 'utf-8')  
  res.send(req.query.callback + '({"something": "rather", "more": "pork", "tua": "tara"});');  
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Test html page:

<html>
	<head>
		<title>jsonp test</title>
		<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>		
		<script type="text/javascript">
            $(function(){				
                $('#jsonThingLink').click(function(e){
                    e.preventDefault();
                    console.log('jsonThingLink clicked');					
                    
                     $.ajax({
                        dataType: 'jsonp',
                        data: "somedata=blahblah",						
                        jsonp: 'callback',
                        url: 'http://localhost:3000/logget?callback=?',						
                        success: function(data) {
                            console.log('success');
                            console.log(data);
                            console.log(data.more);                
                        }
                    });
                });				
            });
        </script>
    </head>
    <body>
        <div id="jsonThing"><a href="#" id="jsonThingLink">test jsonp</a></div>    
    </body>
</html>

Auto reload/refresh page if html changed

When you are twiddling css and constantly tabbing between your editor and browsers, refreshing the browrser can become a chore.

So let’s do some micro-efficiency-dev-process-hacking.

I threw together a quick javascript library that will auto reload the page you are working on IF the html has changed in anyway.

html-crc-reload

Simply include the .js file in your page.
You’ll need to ensure your page references jQuery and that it’s sitting on a web server.

The script will ajax poll itself, check the crc and if different, reload the page.

I develop with lots of side by side windows on a large screen.
This util allows me to stay in the editor window yet see the page refresh when needed.

UPDATE – 2013-05-04

There have been quite a few developments in auto reloading since I posted this.

Firebug, Firefox dev tools and Chrome allow for some aspect of in-page editing (not locally persisted yet).

Here are a bunch of posts on the subject:

I’m going to give the Sublime Text + LiveReload a go since Sublime Text is the pretty damn awesome.

A paid app called Live reload looks pretty cool. Although I haven’t tried it.
And they even talk about other options if it’s not your cup of tea

And Sam Saffron (a developer of Discourse) also touches on the subject