2014-12-23 47 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

哇。謝謝。浪費了我一生的一個小時。 –