主动.js翻转布尔函数

Ractive.js flip boolean function

本文关键字:函数 布尔 翻转 js 主动      更新时间:2023-09-26

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

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')总是undefined,这意味着切换值将始终将所有匹配的键路径设置为true,这不是你想要的。(我刚刚在 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>

为什么不使用 Ractive toggle() 函数?