何时(或如何)使用RactiveJS设置jQuery事件处理程序?

cha*_*ons 2 javascript jquery events ractivejs

我有一个普通的客户端应用程序,主要用jQuery编写.我在一个特定的页面上使用Ractive,它非常有用.但是,所有旧的jQuery事件都不再附加,可能是因为在Ractive被引入之后DOM已经被重新呈现.我尝试在Ractive渲染后设置事件,但这导致了一些奇怪的行为,丢失了DOM元素和东西.我在哪里可以设置那些旧的jQuery处理程序,还是可以的?Ractive呈现是异步发生的,如果是这样,是否有我应该收听的事件?

我试过了

$('.button').click(someHandler);  // <--- Here

getData(function(data){
    ractive = new Ractive({
        el: '.content',
        template: template,
        data: data
    });
});
Run Code Online (Sandbox Code Playgroud)

getData(function(data){
    ractive = new Ractive({
        el: '.content',
        template: template,
        data: data
    });
    $('.button').click(someHandler); // <--- Also here
});
Run Code Online (Sandbox Code Playgroud)

mar*_*pdx 6

超越Rich建议使用Ractive的事件处理(这与Ractive的做事方式最为一致),您也可以使用完整选项:

ractive = new Ractive({
    el: '.content',
    template: template,
    data: data,
    complete: function(){
        $('.button').click(...)

        // or better, use ractive's selector 
        // to limit search to the template.
        // You could use this outside of `complete`
        // as well.
        $( this.find('.button') ).click(...)
    }
});
Run Code Online (Sandbox Code Playgroud)

您可以声明性地使用装饰器来了解元素何时被创建(并销毁),并且可以对其进行引用,而不是为元素捕食.在模板中:

<button decorator='initbutton'/>
Run Code Online (Sandbox Code Playgroud)

然后在代码中:

ractive = new Ractive({
    el: '.content',
    template: template,
    data: data,
    decorators: {
        initbutton: function(node){
            var $button = $(node)
            $button.on('click', ...)

            return { teardown: function(){ 
                //if you need to do anything to teardown...
                $button.off('click', ...) 
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)