2014-12-23 48 views
0

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

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

回答

2

继续从ofrommel的回答中,我想我会尽快解释最初的代码片段中发生了什么,因为它可能在未来有所帮助。

当你调用ractive.set('theData.*.Visible', !'theData.*.Visible'),你设置匹配theData.*.Visible到一个单一的价值,这是!'theData.*.Visible一切 - 而且由于!操作人员只需否定不管它后面,和一个非空字符串被认为是truthy,!'theData.*.Visible' === false。因此,它是这样做的相当于:

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

因此,而不是第二个参数中使用的keyPath,你必须真正得到中的keyPath的价值:

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

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

不幸的是,这并不适用于包含*字符的keypath:

// 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,这意味着触发值将始终集中所有匹配的keypaths到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>

+0

很棒的回答。这对我非常有帮助。你是最好的。 –

1

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

+0

哇。谢谢。浪费了我一生的一个小时。 –