quirkey/sammy — pull request #138 by dvdotsenko (2012-05-21 22:48:24+00:00)
Title: Fix for: Sammy ignoring plugins that were loaded before Sammy finished initializing

This (commit d88b1b108c097d5d33e745ea9a60ba3b1b38ced5) is first half of solution for https://github.com/quirkey/sammy/issues/137

Now Sammy checks if Sammy is in global and extends from it.

Separate patches are written for
0.6.3 (63cd40096791816305a6cb48ccf0fc7bebe5597c) and
0.7.x (d88b1b108c097d5d33e745ea9a60ba3b1b38ced5) branches.

Suggest recommending the following (personally test on own plugins) pattern for plugin writers:

;(function() {
/** @preserve
PluginName module for Sammy.js.

Brief explanation

Copyright (c) YYYY Name contact info
*/
/*
Usage examples
*/

var PluginInitializer = function(Sammy, $){
'use strict'

var pluginName = 'MyPlugin'

// use of [] saves external API names during minification
Sammy[pluginName] = function(app, initarg1, initarg2, etc) {
'use strict'

// here you attach your app to active Sammy object - app

}
} // end of PluginInitializer

//// Uncomment these if you want to make the module AMD-loader compatible.

// if ( typeof define === 'function' && define.amd ) {
// // AMD-loader-compatible (non-)init
// define(function(){
// // To attach the plugin to Sammy,
// // Need to initialize the plugin with Sammy object and jQuery object
// // , when that is available.
// // Example:
// // require(
// // ['jquery','sammyjs','sammyjs.relativehash']
// // , function(jQuery, Sammy, PluginInitializer){
// // PluginInitializer(Sammy, jQuery)
// // // do something with Sammy that expects to have the plug in in place.
// // }
// // )
// return PluginInitializer /* function(SammyObject, jQueryObject) */
// })
// } else {

var global = typeof window === 'object' ?
window :
// with 'use strict' there is a chance 'this' is undefined
typeof this === 'object' ?
this :
(function(){throw new Error("Cannot find 'window' object or its equivalent.")})()

if (!global.Sammy){
global.Sammy = {} // Sammy will extend from this when it loads.
}
PluginInitializer(global.Sammy, global.jQuery)

// }

})(); // please, don't mess with 'window' Make your code resolve it realtime from inside the closure.