gpt4 book ai didi

javascript - Ractive.js 翻转 bool 函数

转载 作者:行者123 更新时间:2023-11-28 19:27:12 24 4
gpt4 key购买 nike

我是 Javascript 新手(从今天开始),我正在使用 Ractive 框架制作一个 Web 应用程序来提供分析产品。我正在尝试创建一个函数来翻转 .on 函数中的 bool 值。我有类似的东西,但它不起作用。有人可以帮我思考一下这个问题吗?

ractive.on('flipBool', function ( ) {
ractive.set( 'theData.*.Visible', !'theData.*.Visible' );
});

最佳答案

根据 ofrommel 的回答,我想我应该快速解释初始代码片段中发生的情况,因为它将来可能会有所帮助。

当您调用 ractive.set('theData.*.Visible', !'theData.*.Visible') 时,您正在设置与 theData.*.Visible 匹配的所有内容 为单个值,即 !'theData.*.Visible - 并且因为 ! 运算符简单地否定其后面的任何内容,以及一个非空字符串被认为是真的,!'theData.*.Visible' === false。所以这相当于这样做:

ractive.set( 'theData.*.Visible', false );

因此,您必须实际获取键路径的值,而不是在第二个参数中使用键路径:

// this...
ractive.toggle( 'foo' );

// ...is equivalent to this:
ractive.set( 'foo', !ractive.get( 'foo' ) );

不幸的是,这实际上不适用于包含 * 字符的键路径:

// this...
ractive.toggle( 'theData.*.Visible' );

// ...is equivalent to this...
ractive.set( 'theData.*.Visible', !ractive.get( 'theData.*.Visible' ) );

// ...which is equivalent to this:
ractive.set( 'theData.*.Visible', true );

因为 ractive.get('theData.*.Visible') 始终为 未定义,这意味着切换该值将始终将所有匹配的键路径设置为 true,这不是您想要的。 (我已经 just opened an issue on GitHub 来解决这个问题。)

因此,目前实现您想要的效果的最佳方法是迭代数组并手动更新所有内容,如下所示:

ractive = new Ractive({
el: 'main',
template: '#template',
data: {
people: [
{ name: 'Alice', visible: false },
{ name: 'Bob', visible: true },
{ name: 'Caroline', visible: true },
{ name: 'Dave', visible: false },
{ name: 'Eric', visible: false }
]
},
flipBool: function () {
var changes = {};
this.get( 'people' ).forEach( function ( person, i ) {
changes[ 'people.' + i + '.visible' ] = !person.visible;
});
this.set( changes );
}
});
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>

<main></main>

<script id='template' type='text/html'>
<button on-click='flipBool()'>flip</button>

{{#each people}}
{{#if visible}}
<p>{{name}} is visible</p>
{{/if}}
{{/each}}
</script>

关于javascript - Ractive.js 翻转 bool 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626357/

24 4 0