开发者

How to access application objects from jquery plugin

In our application we are caching some frequently used data. Recently we have developed a jquery plugin for our web app. Some of the plugin methods needs to access application cache. I tried to access the cache, and result is undefined.

For example:

Application Class

Application(){
cachedObjects = {};
}

<body>
$(function(){
Application();
});

Plugin:

(function( $ ){

var methods = {
initialize : function( options ) { },
getDataFromCache : function() { 
var data = Application.cachedObjects.someObject;// Here, data is undefined.
 }
};

 $.fn.menuPlugin = function( method ) {
 if ( methods[method] ) {
  return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
 } else if ( typeof method === 'object' || ! method ) {
  r开发者_如何学运维eturn methods.initialize.apply( this, arguments );
} else {
}    

};
})( jQuery );

How can i access those application objects?

Any suggestions would be appreciative.

Thanks!


There are many problems here. First you define a function without the function keyword. Second you declare cachedObjects without the var keyword, so it becomes global. I think what you mean is

function Application(){
    var cachedObjects = {};
}

In any case cachedObjects will only be a local variable inside Application, not a property of the Application object (which happens to be a function).

You can declare an Application object in a much simpler way with

var Application = {
    cachedObjects: {}
};

In any case, if you are developing a jQuery plugin you should not create a global variable Application; you can use a variable local to your plugin like

(function($) {// All the definition of your plugin goes in this function
    var Application = ...
})(jQuery);

or store the cached data in a closure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜