I am experimenting with the revealing module pattern for a current project.
I have init methods at the top of several methods where i set up variables and call methods necessarry for the modules to function correctly when they are called by their appropriate event handlers.
I have a init method that looks like this currently:
function init(elem) {
var width,
height,
tipHeight,
tipWidth,
topMargin,
leftMargin;
return appendTip();
};
So this returns a call to the appendTip method.
In another module the set up looks like this:
function init() {
var width = 0,
$siteNavListElem = $('.nav-SiteNav .nav-list > li'),
$subNav = $('.subNav > li > ul');
appendSubNav();
getWidth();
};
So now the开发者_运维知识库re are two calls to individual methods. This code works fine but wondered if it could be any neater?
How do i return both of these? Is returning them the best way to call them?
Thanks.
Actually I am not sure if you are following the revealing module pattern at all. The pattern explains returning a public object that contains the public interface of your object. So returning a function from within a function doesn't really constitute that pattern. For that pattern you are looking at doing something like this
function revealingPattern = function(){
var privateVar = 1;
function prviateFunction(){
//.....
}
function publicFunction(){
//code
}
function pubFunction2()[
//code
}
var publicVariable = 2;
return{
pubFunction1:publicFunction
,pubFunction2:pubFunction2
,pubVariable:publicVariable
};
}()
//use as
revealingPattern.pubFunction1();
Basically all you are returning from the encapsulating function (revealingPattern) is an anonymous object that contains named properties which are the public interface of the revealingPattern object that you are allowed to use.
My gripe with this pattern however is that it doesn't tell you whether a property in the returned object is a function or a variable!
So you might want to refactor your code a bit if you really want to implement the pattern. Otherwise you can pretty much take any approach you would like. They are all valid but just not the revealing module pattern.
精彩评论