问题
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
});
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.
回答1:
Change your code to this:
function giveMeAName() {
return Spine.Controller.sub({
// massive code here
});
}
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.
来源:https://stackoverflow.com/questions/20524880/javascript-variable-declared-as-code-and-reuse