用户脚本中的可重用代码

Reusable code in userscript

我正在尝试编写一个简单的用户脚本(针对 Greasemonkey/Tampermonkey),但我不能完全让它工作。目标是在页面加载时添加 link,然后在元素的 mouseup() 触发时更改 URL (href)。触发代码使用声明元素的新属性,因此需要重新设置它们。

我尝试的主要事情是将可重用代码包装在 function run() { /* code */ } 中(通过必要的调整来做正确的事情,无论是在页面加载时还是在鼠标弹起时调用),但这 returns错误 run() is not defined。我怎样才能在这样的用户脚本中正确重用代码?

$(document).ready(function() {
    // REUSABLE CODE
    var projI=new OpenLayers.Projection("EPSG:900913");
    var projE=new OpenLayers.Projection("EPSG:4326");
    var center_lonlat=(/* variable declaration */);
    var topleft=(/* variable declaration */);
    var bottomright=(/* variable declaration */);
    lat=Math.round(center_lonlat.lat * 1000000)/1000000;
    lon=Math.round(center_lonlat.lon * 1000000)/1000000;
    spn=/* variable declaration */;
});

$(document).ready(function() {
    $('div .olControlAttribution').append('<a id="WMEtoGMM" href=" \
        /* link here that uses above variables */"'+ \
        'target="_blank">Open new page</a>');
});

$('div .view-area.olMap #mouseupElement').mouseup(function() {
    $('#WMEtoGMM').attr('href', 'URL HERE');
});

根据我的理解,您在文档就绪中有一些代码,您希望在文档就绪后能够运行按要求使用这些代码。

但是,更重要的是,您希望能够使用该可重用函数的结果。

所以将代码移到它自己的函数中 returns 一个对象并调用该函数,即:

function calc_values() {
    // call this function something that makes more sense in the context
    // REUSABLE CODE
    var obj = {};  // create a new object to store the values
    obj.projI=new OpenLayers.Projection("EPSG:900913");
    obj.projE=new OpenLayers.Projection("EPSG:4326");
    obj.center_lonlat=(/* variable declaration */);
    obj.topleft=(/* variable declaration */);
    obj.bottomright=(/* variable declaration */);
    obj.lat=Math.round(center_lonlat.lat * 1000000)/1000000;
    obj.lon=Math.round(center_lonlat.lon * 1000000)/1000000;
    obj.spn=/* variable declaration */;
    return obj;
}

$(document).ready(function() {
    // this replaces the original doc-ready call, but doesn't look like it's needed
    calc_values(); 
});

$(document).ready(function() {
    var obj = calc_values();
    // you can now use obj.projI etc to generate your link
    $('div .olControlAttribution').append('<a id="WMEtoGMM" href=" \
        /* link here that uses above variables */"'+ \
        'target="_blank">Open new page</a>');
});

$('div .view-area.olMap #mouseupElement').mouseup(function() {
    var obj = calc_values();
    // you can now use obj.projI etc to generate your link
    $('#WMEtoGMM').attr('href', 'URL HERE');
});