问题描述
我有一个启用了jQuery的javascript应用程序,该应用程序具有一个声明为大量代码的变量.
I have a jquery enabled javascript app that has a variable that is declared as a substantial hunk of code.
var Listings = Spine.Controller.sub({
TPL: Handlebars.compile( $( '#entry-template' ).html() ),
events: //stuff
init: function() //stuff
//a whole bunch of functions
});
我想把这段大块的代码放入一个单独的文件中(因为它长约300行)并用jquery加载它.但是更重要的是,我希望能够将此代码用于两个变量,而不必求助于复制粘贴.
I want to pull this hunk of code into a separate file (as it is about 300 lines long) and load it with jquery. However more importantly, I want to be able to use this code for two variables without resorting to copy-pasting.
推荐答案
将代码更改为此:
function giveMeAName() {
return Spine.Controller.sub({
// massive code here
});
}
然后,您可以像平常一样通过jQuery包含该文件.包含之后,执行以下操作:
Then you can include that file via jQuery as you would normally. After including, do this:
var Listings = giveMeAName();
var SomethingElse = giveMeAName();
如果代码的两种用法略有不同,您也可以传递参数.
You can also pass parameters, if the two uses of the code differ slightly.
这篇关于将Javascript变量声明为代码并重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!