检测Ractive.js中的组件内容更改

Detect component content change in Ractive.js

本文关键字:组件 Ractive js 检测      更新时间:2023-09-26

是否有任何方法可以检测组件的内容何时更改?

例如:

HTML:

<component>
    <div>{{name}}</div>
</component>

JS:

component = Ractive.extend({
    on...: function () {
        // invoked when the inner HTML changes
    }
});

我使用{{yield}},因此内容在父级的上下文中呈现。

现在,我必须将name传递给组件,只是为了观察更改(即使我不需要组件上下文中的值)。(或者我会添加一个可以调用的函数)。

<component changes="{{name}}">
    <div>{{name}}</div>
</component>

有什么想法吗?

这是可能的,但有点麻烦。

http://plnkr.co/edit/YoTZpyTTyCyXijEteGkg?p=preview

    <comp>
        {{name}} hi {{thing}}
    </comp>

 

    comp = Ractive.extend({
        template: '<div>{{yield}}</div>',
        oncomplete: function() {
            var self = this;
            self.partials.content.forEach(function(partial) {
                if (partial.r) {
                    self.parent.observe(partial.r, function(newValue) {
                        console.log(partial.r + ' changed to ', newValue)
                    }, {init: false});
                }
            });
        }
    })

Yield/Content实际上只是一个特殊的分部,因此它将循环该分部中的项目,并为每个关键路径设置一个观察者。

此演示仅适用于像{{foo}}这样的简单表达式。如果你在分部中有更复杂的东西,你必须检查渲染的分部,以确定你想在哪个关键路径上观察父级。