如何立即开火?

时间:2012-08-05 18:32:32

标签: javascript prototypejs

我正在使用原型js绑定一个这样的事件:

$('country').observe('change',function(e) { ... });

如何立即开火?

在jQuery中,我只是简单地使用.triggerHandler('change')。原型中有类似的东西吗?

4 个答案:

答案 0 :(得分:1)

使用load事件。像这样:

// calls addListeners when the document loads
Event.observe(window, 'load', addListeners, false); 

function addListeners() {   

    // called onLoad
    fireOnce();

    // observer for the country dropdown
    $('country').observe('change', function(event) {
        fireOnChange();
    });
}

function fireOnce() {
    // do something
}

function fireOnChange() {
    // do something
}

加载文档时,fireOnce()将会执行。我一直都在使用这种技术。

答案 1 :(得分:1)

如果使用扩展程序是一种选择,我在过去使用event.simulate为此目的取得了成功。

它允许你做类似的事情:

$('country').simulate('change');

答案 2 :(得分:1)

试试这个:

var handler = function(e) {...};
$("country").observe("change",handler);
handler();

或者(不太可读,避免临时变量):

$("country").observe("change",(function(e) { ... return arguments.callee;})());

但是,在这两种情况下,您都无法像预期的那样使用this。此解决方案更适合更常见的回调,例如setInterval

答案 3 :(得分:0)

...如果您知道它存在,并且您知道您没有等待页面加载或等待脚本加载,为什么不只是:

(function (el) {
    if (!el) { return; }
    doSomething(el);
}(document.getElementById("country")));
相关问题