0

我已经安装了运行良好的 Slimbox。

然而,Slimbox 作者已经封装了所有 Slimbox 代码,并在设置一些全局变量后,在 var 中初始化 DOM。

var Slimbox = (function() {

// Global variables, accessible to Slimbox only
var win = window, ie6 = Browser.ie6, options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,

// Preload images
preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

// DOM elements
overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number,

// Effects
fxOverlay, fxResize, fxImage, fxBottom;

// now initialize the DOM
window.addEvent('domready', function() {

// *************
// This is where the problem arises. 
// I call ajax actions here, and some functions which are external to 'domready' 
// *************
pageInit();
setupFormSubmit('product_bid', 'afterPlaceBid');
setupAjaxAction('delete_validate_id_link', 'afterDelete');
setupAjaxAction('move_validate_down_link', 'afterMoveValidate');
//etc...

});
// end the DOM function



function afterMoveValidate(){  
}

function afterDelete() { 
}

// all the Slimbox functions are here too... 
etc..

//end the var Slimbox
})

问题是我的外部函数虽然仍在 var 中,但没有全局范围,而 Slimbox 函数却有。

这在没有 Slimbox 的情况下确实有效,我在其中初始化了 DOM 并具有外部函数。

任何人都可以提供想法/解释吗?

谢谢

4

1 回答 1

0

slimbox 的作者所做的就是实现了模型模式。如果您测试下面的代码,您会注意到您无法访问privateVarprivateFunction从外部访问。但是,您可以通过publicVar`publicFunction.

因此,放入 slimbox 函数(或下面的模型模式)中的所有内容都无法从外部访问,只能从返回的对象中“导出”的部分访问。因为只有那部分会在“slimbox”变量(或下面的模型模式)中。

var modelPattern = (function() {

    // Global variables, accessible to Slimbox only
    var privateVar = 'private';

    function privateFunction() {
        console.log(privateVar);
    }

    return {
        publicVar: 'public',
        publicFunction: function() {
            console.log(privateVar);
        }
    };
})();

modelPattern.publicFunction();
if (!modelPattern.privateFunction) {
    console.log("privateFunction is not defined");
}​

您可以在这个小提琴中看到代码的结果,只需启动您的 javascript 控制台,您就可以看到输出。http://jsfiddle.net/ArE2x/

于 2012-11-13T21:32:10.610 回答