Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Casey Charlton - Insane World

Hang the code, and hang the rules. They're more like guidelines anyway


ASP.NET MVC, JQuery and Cross-View Javascript Events

I wrote a nice little charting component for our site recently, and needed to call a Javascript function in one View (the one that was the main page for charting), from another View (one that went off to the server using Ajax to load up a list of feeds that could be charted).

This would have been traditionally done by putting a function on one View and calling it from another, but this is just a little bit "messy" and prone to breaking. Luckily I decided fairly early on to use JQuery on this site (mostly as I hate writing Javascript and JQuery makes it a doddle). With JQuery I can define a Javascript event across the two views, thereby providing me with a loosely coupled way of achieving my objective.

On my main index page I have:

$('#graphFeeds').bind("add", function(e, feedId, description){
        for(i=0;i<graphedFeeds.length;i++){
            if(feedId==graphedFeeds[i].feedId) return null; }
        var theFeed = new feed(feedId, description, "Green", "Line", 0, 1);
        $('#graphFeeds #table tbody').append(createFeedTableRow(theFeed));
        graphedFeeds.push(theFeed);
   });

And on the view that contains the list of feeds I have:

function addFeed(feedId, description) {
   $('#graphFeeds').trigger('add', [feedId, description]);}

Now by calling the addFeed() function on my list of feeds (I have a little "add to chart" link to the right of each feed), the Javascript event will be fired for the #graphFeeds div ... and the listening handler defined on the index view will go off on it's merry way and add the selected feed into the chart.

Much as I hate Javascript, I love JQuery 

 



Comments

ASP.NET MVC Archived Blog Posts, Page 1 said:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# September 18, 2008 11:25 PM

Dew Drop - September 19, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - September 19, 2008 | Alvin Ashcraft's Morning Dew

# September 19, 2008 9:22 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Casey Charlton

A somewhat passionate and opinionated developer, with occassional sparks of wisdom, and occasional useful information. Check out Devlicio.us!

Our Sponsors

Red-Gate!