Archive for the ‘Javascript’ category

Handy jQuery snippet of the day (sum input fields)

June 19th, 2013

Here is a little handy piece of code I wrote that greatly simplifies summing values across a bunch of text inputs on your page, all you have to do is stick a class on the inputs you want to sum, in my case the class was ‘budget’ and voila, you will have the sum without having to do a bunch of this + that.

var budgetTotal = 0;
$('.budget').each(function (e, s) {
     budgetTotal += parseFloat($(s).val());
});

Backbone collection sorting.

May 14th, 2013

Recently I had a need to sort a list of records in a list by the Date it was created and I wanted to do so using backbone, well it turns out there is a very simple and slick way to get this done, I have included the code snippets below:

The collection:

define([
  'backbone',
  'Models/YourModel'
], function (backbone, model) {
    return backbone.Collection.extend({
        url: '/your_url/',
        model: model,
        sort_key: 'id', // default sort key
        comparator: function (item) {
            return -item.get(this.sort_key);
        },
        sortByField: function (fieldName) {
            this.sort_key = fieldName;
            this.sort();
        }
    });
});

As you can see you just use the comparator: function built into the backbone collections and in my example I am passing a negative so that it will sort descending, the default is ascending so just leave the minus sign off if you want it to work that way. I included the sortByField function here as a convenient way to call it in the code off the collection, it uses the sort_key field in the comparator to organize your collection. Below I have the usage, as you can see, its just a simple call to the string name of the field you want to sort by.

The usage:

new collection().fetch({
                data: { data: "whatever" },
                success: function (r) {
                        r.sortByField("FieldToSortBy");
                },
                error: function (c, r) {
                    alert("Error retrieving the data.");
                },
            });

Be very careful when you set the id of a Backbone model

May 10th, 2013

I have been scratching my head all morning today trying to figure out why a collection I had on my backbone model was getting reset anytime I passed it to my views.  I tried everything, passing the collection to my view in functions, instantiating it in the initialize(), and a few other things that I can’t even remember right now, lol.  Anyways, I noticed down where we were adding items to the collection there was a line that looked like this:

that.model.set(“id”, evt.val, { silent: true });

Notice the lowercase “id” there.  What that is telling backbone is to actually set the id of the model instead of just setting the id to something we had planned to reference down the road, which would be fine in most situations, although I think backbone will do a PUT in those situations because it thinks the model has been saved before.  Anyways, when this was set in my app, it was clearing the collection whenever I passed it around, which was not cool.  All I had to do was change that to an uppercase “Id” and update any reference I had to it and all is well again, my collection stays intact.  I hope this helps someone.

Underscore.js attempts to read commented HTML

April 11th, 2013

I just wanted to throw this out there for anybody trying to figure out why their underscore templates may be failing with properties in their commented html.  It looks to me like underscore.js actually parses everything in the html file in certain situations, I am not fully sure yet but I couldn’t really find much on the web that spoke about it.  I thought I would throw this blog post up so anybody noticing this that has seen it before could chime in and offer some insight into this.  What is weird is that it doesn’t always do it, but only seems to when a change is made at some point to the template being rendered, very strange.  I guess for now my only alternative would be to remove the <%= %> in my comments.  If anybody has some alternatives I am all ears.

How to get all items from an HTML table with JQuery

April 9th, 2013

Here is a little snipped that saved me a lot of manual code writing if you are needing to iterate over a set of rows in a table you have on your webpage. Just simply use the “gt(0)” which according to the JQuery API documentation “select all elements at an index greater than index within the matched set.” Then just pair that with tr: in front of it to select all the table rows of your table and voila, you have all your rows. You can then use the .each method to do the iteration. Don’t forget to change #tableId to whatever you called it in your html, enjoy.

$("#tableId tr:gt(0)").each(function () {
    //perform logic here
});

Add some sweet logging to your Javascript/Node.js apps with Winston

March 19th, 2013

If you are looking for a logging solution to your javascript or node.js apps, look no further, enter Winston.  This little tool can write logs from your apps to a file, to the console, or to a database and you can even query the logs with its own built in syntax, how sweet is that?  Anyways, I have included below the code snippets that is needed to get it going, check it out:

//by default, Winston is set to log to console 
var winston = require('winston');

 winston.log('info', 'Hello distributed log files!');
 winston.info('Hello again distributed logs');

//you can change that behavior by doing something like this:
winston.add(winston.transports.File, { filename: 'somefile.log' });
winston.remove(winston.transports.Console);

Here is the github repo for further reading if you are considering this tool https://github.com/flatiron/winston

Pretty simple, just three lines of code and you are logging, just slap a winston.info() anywhere you want to see some info and you are good to go, enjoy!!

Using Socket.IO with Backbone.js

March 6th, 2013

I work on a lot of different projects, some for work and some for fun and some on the side.  I have been working on a social application here lately that will have lots of topics and within those topics they will have comments.  I felt like the ‘Room’ concept of socket.io would be a good fit for this idea so I began implementing it for this project.  When I first set up socket I was having a problem because stupid me had some javascript that was formatted incorrectly and the engine was not throwing an error with it because it translated to good javascript.  In the meantime while I was doing all of that I had stuck the socket connection in a global variable so it was only making one connection, that does seem to be how you would want your socket.io application to be setup anyways.

I have included the final code below of the solution that is working for me with my backbone views, it turns out I had to create a new socket.io connection each time a topic was clicked on by the user, due to the fact that I am ‘joining’ them to that room, identified by the TopicID.  When I had the socket defined globally, I was getting duplicate messages back to my clients and my only reasoning was that I had the single connection so my clients were getting those dupes back at them.

If you have anything you could throw in for me with input, I would really appreciate it as I think this setup is not a very scalable one, thanks.

//server.js
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
  console.log('Socket Connection Made - Server Side');
  socket.on("leaveRoom", function(data){
      console.log('Leaving room ' + data.room);
      socket.leave(data.room);
  });
  socket.on("setRoom", function(data){
      console.log('Joining room ' + data.room);
      socket.join(data.room);
  });

  socket.on('comment', function(data) {
    console.log('Emitting comment');
    socket.broadcast.to(data.room).emit('comment', data.comment);
  });
});

//client.js
//in backbone view initialize()
var url = "http://localhost:3000";
this.socket = io.connect(url);
this.socket.on('connect', function () {
    that.socket.emit("setRoom", {room: that.model.get("TopicId")});
});
this.socket.on('comment', function (data) {
     $('#commentsList').prepend(data);
});

//here is the code to tell server a new comment has been published
that.socket.emit('comment',{ comment: msg, room: that.model.get("TopicId")} );

Calculate Percentages from Two HTML inputs with javascript

March 1st, 2013

I recently had a need for a generic way to calculate 100% across two input boxes, for instance if you entered 50% in one box it would go over and put 50% in the other, and vice-versa.  Well, I have accomplished this with a little help from jQuery and for formatting I use the excellent javascript library called autoNumeric found HERE.  Make sure you use the one I have referenced here in the fiddle as others would not let the autoNumericGet work, it must have been older versions. I have linked my jsFiddle below, check it out, run the sample and see how it works, hope this helps someone.

If you can’t see, the fiddle, here is a link to it:
http://jsfiddle.net/eddie_d_2000/H92FC/

Select2 3.2 Add Custom Clickable item to dropdown.

February 15th, 2013

There are a few folks asking how they can insert something to the bottom of the Select2 javascript control and I have came up with a solution as shown below in my jsfiddle.  All I am doing is making use of the query function that select2 provides as outlined here: Select2 Documentation.  Also take note of what I am returning in the results, basically I am making use of select2’s ability to create grouped headers and use a “children” parameter to show that list.  All I had to do was add in whatever I wanted my bottom link to say and voila, I have an entry to allow the user to click on and perform an action.

NOTE:  Newer versions > 3.2 do not show html as output, the newer version of the control is overriding the output somehow and just rendering the text, I was too lazy to figure out what is going on so I just thought I would give a heads up.

UPDATE:  The Select2 (currently at 3.4.5) control has been updated with the escapeMarkup parameter, simply add a line like this to your options of your select2 element:  “escapeMarkup: function (m) { return m; }” and you can have clickable links back in your dropdown.

Here is the pull request for it: https://github.com/ivaynberg/select2/pull/1817?source=cc

Need a simple CSS layout for messages?

February 12th, 2013

I am working on a phonegap side project and I have a need to display a list of messages that users will be entering into a system and I couldn’t really find a good example online so I wrote one using pure CSS and Javascript. All you need to do now is hook it into a templating library and you got what you need, enjoy!!

http://jsfiddle.net/eddie_d_2000/WNyPt/embedded/result/