我正在使用CakePHP 2.3.8,我試圖從knockout.js視圖模型中調用一個函數,但我在理解正在發生的事情時遇到了一些麻煩。從外部視圖模型的knockout.js調用函數
如果設置了一個特定的變量(在PHP中),那麼我想顯示一個div,但我無法使其工作。當我從PHP代碼中調用它時,div不會顯示,但是方法中的警報消息會觸發,所以我知道代碼已經到達。
<div data-bind = "visible: someDiv">
I'm visible
</div>
這裏的淘汰賽視圖模型
function myViewModel(){
var self = this;
self.someDiv = ko.observable(false); //the div starts out hidden
self.editing = ko.observable(false);
//if the editing variable is changed, display someDiv
self.editing.subscribe(function(){
alert('edit changed'); //this alert triggers every time, even from the PHP call
self.someDiv(true); //someDiv only shows if I call from within the view model
});
//if I manually change editing to true from within the viewmodel, the div shows
//self.editing(true);
}
ko.applyBindings(new myViewModel());
這裏是PHP代碼發起的事件序列
echo $this->Html->script('knockout-2.3.0');
echo $this->Html->script('viewmodel');
//if the edit variable is set, the "someDiv" should be set to true
if(isset($edit)){
<script>
window.vm = new myViewModel();
window.vm.editing(true); //this will trigger the alert from the subscribe function, but the div doesn't display
</script>
}
爲什麼當我編輯值從PHP股利更改爲true不顯示,但如果我從viewmodel中更改它顯示?
它甚至有可能做我想做的事情嗎?
編輯
我在JS文件將綁定到我的視圖模型。我是而不是在PHP文件中再次應用綁定。
我的意思是「變量被設置(在PHP中)」是數據的來源源於PHP,儘管它是JavaScript設置值的最後。我一直是短了我上面的例子,所以實際上它會是這樣(不,它使多大的差別)
//if the edit variable is set, the "someDiv" should be set to true
if(isset($edit)){
<script>
window.vm = new myViewModel();
window.vm.editing(<?php echo $edit; ?>); //this will trigger the alert from the subscribe function, but the div doesn't display
window.vm.another(<?php echo $something_else_here; ?>);
</script>
}
我更新了我的原始帖子,以清除「PHP設置問題」。對於那個很抱歉。就能夠訪問編輯的可觀察對象而言,我怎樣才能從視圖模型之外做到這一點? – user3476345 2014-09-26 14:43:10
@ user3476345如前所述,問題在於您正在初始化視圖模型兩次。正如我之前提到的,在JS中設置'window.vm = new myViewModel()',然後在你的PHP或w/e中調用applyBindings,你試圖使用'window.vm'來設置值,而不是新的一個。 – 2014-09-26 16:44:26
感謝您的幫助。 – user3476345 2014-09-26 20:09:28