Shazwazza

Shannon Deminick's blog all about .Net, Umbraco & Web development

Injecting JavaScript into other frames

September 9, 2010 18:44 by Shannon Deminick

The beautiful part of JavaScript is that it is ridiculously flexible and lets you do things that ‘probably’ shouldn’t be done. Here’s a good example of that.

During uComponents development I stumbled upon a situation where I needed to attach a JavaScript method to the top-level frame from inside of an iframe. Well in fact it turns out this is quite easy, you can do something like this:

window.top.doThis = function() { alert("woot!"); }

However, since we’re attaching the ‘doThis’ method to the main frame from an inner iframe, when the inner iframenavigates to another page, this function will no longer exist on the main frame… So this clearly isn’t going to work if we want to be able to call the ‘doThis’ method from the inner frame no matter when and where it navigates to… Conundrum!

So the next possibility is to try to just inject a script block into the main frame from the iframewhich actually does work in Firefox and Chrome but fails in Internet Explorer and Safari. (This snippet of code requires that you have jQuery loaded in the main frame)

var js = "function doThis() { alert('woot!'); }"; var injectScript = window.top.$('<script>') .attr('type', 'text/javascript') .html(js); window.top.$("head").append(injectScript);

In the above, we’re creating a string function, creating a <script> block with jQuery, appending the string function to the script block and then appending this script block to the <head> element of the main frame. But as i said before, Firefox and Chrome are ok with this but Internet Explorer and Safari will throw JavaScript exceptions such as: Unexpected call to method or property access

Ok, so unless you don’t want to be cross browser, this isn’t going to work. It took me a while to figure out that you can do this, but this does work. Yes it looks pretty dodgy, and it probably is. In reality, attempting to do something like this is pretty dodgy to begin with. So here it is (this works in Internet Explorer 8 (probably earlier ones too), Firefox 3.6 (probably earlier ones too) and Chrome 5 (probably earlier ones too) and i didn’t get around to testing Safari but I am assuming it works):

var iframe = window.top.$("#dummyIFrame"); if (iframe.length == 0) { var html = "<html><head><script type='text/javascript'>" + "this.window.doThis = function() { alert('woot'); };" + "</script></head><body></body></html>"; iframe = window.top.$("<iframe id='dummyIFrame'>") .append(html) .hide() .css("width", "0px") .css("height", "0px"); window.top.$("body").append(iframe); }

So i guess this requires a bit of explanation. All browsers seem to let you create iframes dynamically which also means that you can put whatever content into the iframes while it’s being created, including script blocks. Here’s what we’re doing:

  • checking if our ‘dummy’ iframe already exists (since we don’t want to create multiple dummy iframes since we only need one), if it doesn't:
  • create an html text block including the script that will attach the ‘doThis’ method to the ‘this.window’ object (which for some reason will be referring to the window.top object)
  • next we create an iframe element and append the html text block, and then make sure the iframe is completely hidden
  • finally, we append the iframe to the main window’s body element
window.top.doThis();

Nice! So this pretty much means that you can create code from an inner frame and attach it to a different frame, then have that code run in the context of the main frame with the main frame’s objects and script set.

One last thing that i found out you can do, though i wouldn’t recommend it because i think it might start filling up your memory. But this is also possible:

var html = "<html><head><script type='text/javascript'>" + "this.window.doThis = function() { alert('woot'); };" + "this.window.doThis();" + "</script></head><body></body></html>"; iframe = window.top.$("<iframe id='dummyIFrame'>") .append(html);

All that is happening here is that I’m attaching the ‘doThis’ method to the main frame’s window object, calling it directly after and then creating an iframe in memory with this script block. The funny part is that the method executes straight away and I haven’t attached the iframe to the DOM anywhere!

Umbraco 4.1 Benchmarks Part 1

April 16, 2010 09:42 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
This is the first installment of what will hopefully be many Umbraco benchmark reports created by various members of the core team in the lead up to the launch of Umbraco 4.1. This benchmark report is about the request/response performance of the Umbraco back-office. This compares 4 different configurations: 4.0.3 with browser cache disabled (first run), 4.0.3 with browser cached files, 4.1 with browser cache disabled and 4.1 with browser cached files. These comparisons have been done by using newly installed Umbraco instances with ONLY the CWS package installed. The benchmark results were prepared by using Charles Proxy.
Test Stats 4.0.3 4.0.3
client cached
4.1 4.1
client cached
Content app Completed Requests 68 7 46 6
Response (KB) 687.05 72.48 431.41 32.54
Edit content
home page
Completed Requests 50 2 34 1
Response (KB) 385.10 47.28 343.36 12.07
Expand all
content nodes
Completed Requests 17 17 16 16
Response (KB) 18.47 18.47 13.96 10.85
TOTALS Completed Requests 135 26 96 23
Response (KB) 1063.62 138.23 788.73 55.46

Note: the above is based on <compilation debug=”false”> being set in the web.config. If it is set to true, the compression, combination and minification for both the ClientDependency framework and ScriptManager is not enabled. Also, this is not based on having IIS 7’s dynamic/static compression turned on, these benchmarks are based on Umbraco performing ‘as is ‘ out of the box which will be the same for IIS 6.

Though there’s only 3 tests listed above, these results will be consistent throughout all applications in the Umbraco back office in version 4.1.

The 4.1 difference:

  • In 4.0.3, all ScriptResource calls generated by ScriptManager were not being compressed or minified. This was due to a browser compatibility flag that was set in the base page (this was probably very old code from pre v3!).
  • Script managers in the back-office have the ScriptMode=”release” explicitly set (for minification of ScriptResource.axd)
  • The ClientDependency framework is shipped with 4.1 and all of the back office registers it’s JavaScript and CSS files with this framework. This allows for:
    • Combination, compression, minification of dependencies
    • Rogue script/style detection (for those scripts/styles that weren’t registered with the framework will still get compressed/minified)
    • Compression/minification of specified Mime types, in this case all JSON requests in the back office (namely the tree)
    • Compression/minification of all JavaScript web service proxy classes (‘asmx/js’ requests that are made by registering web services with the ScriptManager
  • Much of the back office client scripting in 4.1 has been completely refactored. Most of the JavaScript has been rewritten and a ton of file cleanup has been done.

Compared to 4.0.3, this is a HUGE difference with some serious performance benefits!

ClientDependency now supporting MVC

April 7, 2010 09:38 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
I’m please to announce that the ClientDependency framework now supports MVC! It’s very easy to implement using HtmlHelper extension methods. Here’s some quick examples:

Make a view dependent on a CSS file based on a path defined as “Styles”

<% Html.RequiresCss("Content.css", "Styles"); %>

Make a view dependent on jQuery using a full path declaration:

<% Html.RequiresJs("/Js/jquery-1.3.2.min.js"); %>

Rendering the Style blocks and defining a global style path:

<%= Html.RenderCssHere(new BasicPath("Styles", "/Css")) %>

Rendering the Script block (no global script path defined):

<%= Html.RenderJsHere() %>

There’s still a provider model for MVC but it uses a slightly different implementation from Web Forms. The same compositeFiles provider model is used but instead of the fileRegistration provider model that is used in Web Forms, a new mvc renderers provider model is used. A renderer provider is similar to the Web Forms fileRegistration providers but instead of registering the markup in the page using the page life cycle, a renderer provider is used to render out the html block necessary to embed in the page.

All of the functionality that existed in Web Forms exists in MVC. You can make as many views that you want dependent on as many of the same or different client files that you want and the system will still sort by position and priority and remove all duplicate registrations. Rogue scripts & styles still get processed by the composite file provider in MVC. Currently however, if you place user or composite controls on your views that have Client Dependencies tagged with either the control or attribute method used in Web Forms, these will not be registered with the view and output with the renderer. 

MVC pages have been added to the demo project as examples so have a look! You can download the source HERE

For full details and documentation go HERE

sIFR vs. cufón: Text replacement and you

April 1, 2010 01:40 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
There are two reasons I use dynamic text replacement:

  1. Plain text in a browser window is never as smooth as it is in the design (except in Safari),
  2. The designs I'm given almost always use fancy (non-web based) fonts for headings, intro text etc.

Currently I subscribe to two solutions, both client-side: sIFR and cufón. If you want a quick answer to "what should I use?" then here it is: if you want replacement for long sentences and headings, use sIFR. If you want replacement for a few words on a button or in a menu, use cufón. If you want to know more, read on...

sIFR

How sIFR works

sIFR uses javascript to dynamically embed a Flash object in the place of specified HTML text elements. The Flash object is essentially an empty SWF (compiled Flash file) which includes the characters of the font you want to use. When javascript embeds the SWF in the HTML, it passes the SWF arguments such as text-content, font-size, color, rollover behaviour and many more. Some of these properties javascript takes from the CSS applied to the text, and some are overridden by sifr-config.js, which is a human-readable config file containing additional formatting tweaks.

How to use sIFR

  1. Download the source (only sifr.js, sifr-config.js and sifr.css are actually needed).
  2. Generate a font SWF from a True Type Font file. You can do this manually with Adobe Flash (like this) but it is easier to use this online generation tool.
  3. Link to sifr.css in the head of your HTML page.
  4. Link to both scripts in the head of your HTML page, first sifr.js, then sifr-config.js
  5. Edit sifr-config.js to read in the font SWF you created and use CSS selector syntax to select the HTML text elements you want to replace.
  6. Tweak away in sifr-config.js until the text looks right when sIFR is both enabled and disabled, in case the user is missing Flash (iPhones don't have Flash as of early 2010!).

cufón

How cufón works

cufón is entirely javascript and works in all major browsers (including IE6). You still need to generate a font file, but this is output to a javascript file similar in size to the equivalent sIFR SWF font file. cufón looks at selected blocks of text and replaces each word with a dynamically generated image (using the HTML <canvas> tag), or in IE's case, a VML object (Vector Markup Language). As a consquence of this, increasing the text size of the page either doesn't affect cufón-replaced text or expands the image, blurring it. Except in IE, which scales the text perfectly.

How to use cufón

  1. Download the source (all you need is cufon-yui.js)
  2. Generate a font file from a True Type Font. You are unfortunately dependent on this online generator.
  3. Link to cufon-yui.js in the head of your HTML page. Beneath it, link to any font files you've generated.
  4. You may also want to create another file, cufon-config.js, to hold selector information much the same way as sifr-config.js does.
  5. Populate cufon-config.js with what HTML text elements you want to replace.

Legality

Font foundaries are seemingly run by people who are very freaked out that their fonts are going to leak for free. Hence, the vast majority of fonts can't legally be embedded directly into the CSS (what, you didn't know about that? It's been around a while in some form or another - the @font-face directive allows you to supply the font file for obscure font-families - but it's only legal with open source fonts).

Because sIFR uses Flash, and Adobe has a cordial agreement with the font foundaries in Switzerland (or wherever) which allows anyone to embed pretty much any font in a .swf, sIFR is totally legal. cufón... cufón not so much. Although both supply a compiled/obfuscated font resource in .swf/.js format respectively, and are basically the same from the font foundaries' point of view, they haven't got around to adding "Allows embedding using javascript methods" to their fonts' terms of use agreements. And I wouldn't count on it...

So in short, use cufón. Go on, it's young and fresh and rad! Push the font foundaries to legalise it! But remember: you read that in a blog post...I'm not going to be your lawyer if they come after you.

Comparison

sIFR cufón
Core file-size (not including fonts) 30KB 18KB
Independent of Flash ×
Resizes nicely ×
Cursor-selectable text ×
Doesn't flicker on load ×
Independent of online font-generator ×
Online font-generator supports Open fonts (.otf) ×
Supported in all browsers
Degrades gracefully
Legal ×

ASP.Net Client Dependency Framework RC1 Released!

March 19, 2010 08:13 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
With the community feedback, bug reports, patches, etc… I’ve managed to find time to upgrade this library to a release candidate status. We do use this framework in many production websites but it was great to hear from other in regards to specific bugs that were found relating to particular environments. These bugs have all been fixed up and this library is looking very stable.

You can download the binaries here.

Better yet, I’ve put together a near complete documentation library on CodePlex here !!

I still think the best way to learn about this project is to download the source code from CodePlex here and have a look at the demo web application included.

Moving forward, the next phase for this library is to add MVC support and another file registration provider called PlaceholderProvider which will give you even more granular control over where dependencies can be rendered in your markup. MVC support should be fairly straight forward and we’ll include a demo project for this as well.

Well definitely be releasing a final version soon after the next Umbraco 4.1 release candidate is released (which will hopefully be fairly soon!)

Happy day! Any and all feedback, bug reports and patches are definitely appreciated!

A Few New Controls in Umbraco 4.1

January 20, 2010 08:07 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
Currently the codebase in Umbraco 4.0.x uses quite a few iframes to render ‘controls’ as this functionality has existed this way from way back in the day and had never been upgraded… until now!

IFrames should be used sparingly, they have their uses but to render an iframe instead of a User Control is just adding overhead to the page, the client and server cpu/memory consumption and is not so cool. Here’s a nice benchmark on iframe performance: http://www.stevesouders.com/blog/2009/06/03/using-iframes-sparingly/ . As you can see, you should use iframes ONLY when completely necessary.

So on to the good news… Here’s some new controls that have been created in 4.1 (which will remove many of these iframes and make things a whole lot nicer to use)

  • /umbraco/controls/Tree/TreeControl.ascx
    • Will render a new tree based on the properties set
    • This makes the following Obsolete: treeInit.aspx, treePicker.aspx  (though, these pages are still used to load trees in modal windows for pickers but shouldn’t be used directly in your code)
      • Both of these pages now simply wrap the TreeControl
    • Example usage:
      <umb2:Tree runat="server" ID="DialogTree" 
          App="media" TreeType="media" IsDialog="true" 
          CustomContainerId="TinyMCEInsertImageTree" ShowContextMenu="false" 
          DialogMode="id" FunctionToCall="dialogHandler" />

    • There’s quite a few other properties that allow you to customize the tree to your needs
    • There’s also a very in-depth JavaScript API
  • /umbraco/controls/Images/ImageViewer.ascx
    • This is a nifty ajax control that will take a media item id and display the image
    • There’s a simple JavaScript library attached to it that allows you to dynamically update the media id to force an ajax request to refresh the image (amongst other methods)
    • This makes the following Obsolete: /umbraco/dialogs/imageViewer.aspx
      • The old codebase for imageViewer has been retained (though it should probably just wrap this control :)
    • Example usage:
      <umb3:Image runat="server" ID="ImageViewer" 
          ViewerStyle="ThumbnailPreview" LinkTarget="_blank" 
          ClientCallbackMethod="onImageLoaded" />

  • /umbraco/controls/UploadMediaImage.ascx
    • This control is essentially what you see when you load up TinyMCE, select the insert image button, then click on the ‘Create New’ tab. It contains the logic to enter a name, select a file to upload and select the media tree node to upload it to.
    • There’s a handy JavaScript callback method you can define so that it’s executed once the upload is complete. Tons of parameters are passed to the callback containing all of the information about the file/image.
    • This makes the following Obsolete: /umbraco/dialog/uploadImage.aspx
    • Example usage:
      <umb4:MediaUpload runat="server" ID="MediaUploader" 
          OnClientUpload="onFileUploaded" />

Now, on to the ‘pickers’! There’s quite a few picker controls in the codebase that all essentially do the same thing but the code for them was pretty much replicated everywhere, so i decided to streamline the whole thing which should make it quite easy for anyone to make their own pickers!

  • umbraco.controls.BaseTreePicker.BaseTreePicker (in the umbraco.controls assembly)
    • (yes i know the namespace and control are the same name, but that’s the way it is currently! :)
    • From the name, you would probably determine that this control is an abstract control… and you’d be correct.
    • This control implements: IDataEditor (so that it can be used as the data editor for Umbraco data type controls), and INamingContainer for obvious reasons.
    • This control exposes many properties and methods for you to modify and override to customize the picker.
    • The abstract properties are ModalWindowTitle (the title of the window that gets displayed) and TreePickerUrl (the URL to load in the modal window that is displayed)
    • This pretty much handles everything for a basic tree picker and the JavaScript has been refined to use real classes! Wow! ;)
  • umbraco.editorControls.mediaChooser (in the umbraco.editorControls assembly)
    • This is the umbraco data type to select a media item from the media tree
    • It’s been upgraded to inherit from BaseTreePicker and overrides the JavaScript rendered to support Tim’s new fandangled media picker (similar to the TinyMCE media picker)
  • umbraco.editorControls.pagePicker (in the umbraco.editorControls assembly)
    • This is the umbraco data type to select a content node from the content tree
    • It’s been upgraded to inherit from BaseTreePicker … it really doesn’t have any special functionality apart from setting the title and the tree picker url since all of the required functionality is in the BaseTreePicker
  • umbraco.controls.ContentPicker (in the umbraco assembly)
    • This pretty much does the same thing as all of the above controls, actually it’s nearly identical to the pagePicker only you have to specify the AppAlias and TreeAlias to load for the picker.
    • It’s been upgraded to inherit from BaseTreePicker also

So basically, everything will look pretty much the same, but will be a lot faster and MUCH easier to develop with if you’re creating custom packages or whatever. It’s all backwards compatible (apart from the JavaScripting) but under the hood is much different.

So now at least when you load up the TinyMCE insert image dialog, you end up with 1 frame (the modal dialog) instead of 4!

Oh yeah, and this hasn’t been checked in to the 4.1 branch as of today… perhaps next week!

Client Dependency Framework Beta Released

September 29, 2009 22:06 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
I’ve posted a new Beta release on CodePlex, you can get it here: http://clientdependency.codeplex.com/Release/ProjectReleases.aspx. On the releases tab includes a sample web site that has most of the functionality that you can do so please download it for a documentation reference.

Newest changes & additions

  • Namespace and codebase changes/steamlining
  • Proper versioning added
    • Versioning is done on a global basis in the config
    • Old versions are retained and can still be accessed from the Client Dependency URL that was previously used (if necessary)
    • Versioned composite files names are prefixed with the version number (i.e. version 2 files will be prefixed with '2_') so it's easy to figure out which files are old
    • The composite file map also reflects which composite file sets are under a specific version
  • Provider model extended to support 2 types of providers:
    • File Registration Providers
      • Still comes with 2 providers: page header provider and a lazy loading JavaScript client based provider
    • Composite File Providers:
      • Comes with the standard provider: CompositeFileProcessor
      • You can implement your own provider to customize the way that files are combined, compressed, minified, etc... if the standard provider isn't exactly what you are after
  • Forced providers! You can now force a dependency to use a particular provider. This can be useful if you want to ensure that a particular script or stylesheet is rendered on to the page differently. For example, you may want to ensure that a script is lazy loaded (using the lazy load provider) but the rest are rendered in the page header.
  • Utility methods added to the ClientDependencyLoader for more dynamic implementations
  • A test website is included in the release which doubles as documentation, it includes:
    • Standard page header provider example
    • Forced providers example
    • Lazy load provider example
    • Dynamically registering dependencies in your code behind
    • Registering dependencies with attributes and via aspx controls

Things //TODO:

I’ve finished off versioning so at least i can cross that off from the previous list. But there’s still more to do:

  • Implement functionality for jQuery CDN
    • This will be a new control/attribute to easily include jQuery in your project
    • You will have the option to select which CDN you want to use (Microsoft or Google), or you can supply an address (like your own CDN/web server)
    • Though this framework will be included in Umbraco 4.1, we’ll be leaving this functionality out of the Umbraco build as we realize that there are quite a few installs that operate behind a firewall that won’t have access to the CDN.
  • Implement skeleton for Microsoft AJAX 4 CDN
    • Again, this will be another new control/attribute to easily include Microsoft’s new brand of AJAX with their CDN solution
  • Add support for MVC
  • Support for JS/CSS Minification with options to disable per dependency
    • The reason this hasn’t been implemented yet is that I’ve found a lot of scripts/stylesheets break with minification so we need to be able to turn this on/off on a per file basis
  • Some more documentation/examples in the example web application

jQuery Vertical Align

April 7, 2009 20:09 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
UPDATED! (2009-04-29)

An easy way to vertical align elements with one line of code:

$('.innerText').VerticalAlign();  

I've removed the parameters as it turns out if you pass in a negative offset using padding, IE6 throws an error and JavaScript fails to continue executing. If you get the following error in IE6 debugging, it may be due to passing in a negative value to a padding css attribute, or similar:

  • invalid argument jquery J[G]=K

It's fairly easy to structure your html to not require a vertical align offset so it's really not needed anyways.

It also supports a couple of parameters:

  • offset = the number of pixels to offset the vertical alignment
  • usePadding = true/false. the default is false which uses a margin to align, if set to true, it uses padding
$('.innerText').VerticalAlign({offset:-20, usePadding:true})

Get the source:  VerticalAlign.zip (290.00 bytes)

jQuery popup bubble extension

April 7, 2009 04:30 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.
UPDATED (2009-05-25)!

Here's a quick and extensible framework to enable popup windows, popup bubbles, or popup anything. Currently the framework doesn't create extra DOM elements or style anything differently. It relies on the developer to create the DOM element that will be the popup bubble (or whatever). This extension give you the flexibility to bind any number of events to show or hide the bubble. It also supports having the bubble hide on a timer and comes with a complete event model allowing you to intercept the hide and show bubble events (and cancel them if needed) and fire your own methods upon completion.

I've included a full demo html page to demonstrate some different implementations.

Here's an example of the usage:

$(".bubble").AlertBubble(
{
	fadeTime: 500,
	hideEvent: [
		{selector: $("#hideButton"), event: "click"}
	],
	showEvent: [
		{selector: $("#showButton"), event: "click"}
	],
	showOnStart: true,
	text: "I am a bubble",
	hideTimer:2000
});
The above code turns the elements with the class of .bubble into an AlertBubble. The parameters passed in are the parameters that are supported by this class:
  • fadeTime: the milliseconds to fade in/out. Default = 200 
  • text: the text to show in the html element. If set to false (by default) it will use the markup that currently exists in the element.
  • hideEvent/showEvent
    • Allows you to add/remove as many event handlers to show or hide the alert bubble
  • showOnStart: if the bubble should show on page load or only when showOnStart exists
  • hideTimer: If set, then the bubble will hide after the set number of milliseconds after shown. Default is false.
  • onBeforeShowCallback: a function to call before the bubble is shown. If a callback is specified, it must return true for the code to proceed to show the bubble.
  • onBeforeHideCallback: a function to call before the bubble is hidden. If a callback is specified, it must return true for the code to proceed to hide the bubble.
  • onAfterShowCallback: a function to call after the bubble is shown.
  • onAfterHideCallback: a function to call after the bubble is hidden.

The extension also has a simple API that can be accessed to show/hide the bubble on demand as well as using events. This is done by storing the API object for the popup bubble extension in the jQuery data object for the popup bubble selector.

API methods:

  • showBubble()
  • hideBubble()

To access the API, you can retrieve it from the jQuery data object with the key "AlertBubble":

var api = $(".myselector").data("AlertBubble"); 

Example:

$(".bubble").each(function() {
	var api = $(this).data("AlertBubble");
	if (api != null) {
		api.hideBubble();
	}
});

Super easy jQuery events

March 26, 2009 09:08 by Shannon Deminick
This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.

I've been using jQuery for a while but haven't really been using it much in the form of building custom classes or libraries. I've been working on re-developing Umbraco's JavaScript tree using jsTree (which is great by the way!) and have been writing a JavaScript library to support it. As with most code libraries, events play an important role in writing clean and effective code. In the past I've always used simple callback methods for "event handling" in JavaScript, but this isn't really an event system since it doesn't allow more than one subscriber. After some quick research, jQuery has this all built into the core, and by adding a couple very simple methods to your JavaScript classes, they will instantly support an event model!

Quick example: 

var myObject = {
	addEventHandler: function(fnName, fn) {
		$(this).bind(fnName, fn);
	},
	removeEventHandler: function(fnName, fn) {
		$(this).unbind(fnName, fn);
	},
	doSomething: function() {
		$.event.trigger("somethingHappening", [this, "myEventArgs"]);
	}
}

The above example is an object defining 2 functions to manage it's event model and another method which raises an event called "somethingHappened" with an array of arguments that will get bubbled to the event handlers.

To subscribe to the events is easy:

function onSomethingHappening(EV, args) {
	alert("something happened!");
	alert("sender: " + args[0]);
	alert("e: " + args[1]);
}
//subscribe to the event:
myObject.addEventHandler("somethingHappening", onSomethingHappening);

You'll notice that the above event handler function has 2 arguments, one called "EV" and one called "args". The EV parameters is the jQuery event object and the second one is the custom arguments object that was created when raising the event.

Since Umbraco's admin section uses an iframe approach, i though that managing events between the iframes would be an issue since they are all using seperate jQuery instantiations, but by raising and consuming events with the above method, this is no problem.

Recent Tweets

Twitter May 14, 14:14
blogged: script to fix media paths when changing vdirs or media root paths in #umbraco http://t.co/w1csEtceu1

Twitter May 10, 18:27
@darrenferguson probably better discussed on a forum thread I think :-) @sitereactor

Twitter May 10, 17:55
@darrenferguson and won't work in LB cuz a servers file will b stale when it goes to sleep @sitereactor

Twitter May 10, 17:53
@darrenferguson sorry, bad wording... You'd have to write that feature but it'd be pretty simple @drobar @sitereactor

Twitter May 10, 08:34
@sitereactor ... wouldn't work for LB scenarios though @darrenferguson @drobar

Follow me