Javascript variable declared as code and reuse

∥☆過路亽.° 提交于 2020-01-06 06:50:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!