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
Posted
09-17-2008 1:50 PM
by
Jak Charlton