2017-04-23 81 views
0

我正在使用帶有可觀察插件的Durandal來啓用ES5獲取器和設置器。我創建了一個簡單的小工具,需要一個值,並將其綁定到一個文本框:Durandal小部件不會在父視圖模型中更新值

這裏的小部件的viewmodel.js:

define([], function() { 
    var ctor = function() { 
     this.activate = function (settings) { 
      this.value = settings.value; 
     } 
    }; 

    return ctor; 
}); 

而這裏的小部件的view.html:

<span> 
    This textbox is in the widget: 
    <br /> 
    <input type="text" data-bind="value: value" /> 
</span> 

當使用小部件時,如果該值作爲ko.observable傳入,那麼一切都按預期工作。但是,如果我使用observable插件提供的ES5 getter/setter方法,那麼修改小部件中的值不會導致更新父視圖模型。修改父視圖中的值不雖然更新窗口小部件:

define(['durandal/app', 'knockout'], function (app, ko) { 
    var ctor = function() { 
     this.value = ko.observable('Test'); // This works as expected 
     this.value = 'Test'; // This does not work 
    }; 
    return ctor; 
}); 

這裏的父視圖:

<section> 
    <h1>Widget Test</h1> 
    This textbox is not in the widget: 
    <br /> 
    <input type="text" data-bind="value: value" /> 
    <br /><br /> 
    <div data-bind="widget: { kind: 'testWidget', value: value }"></div> 
</section> 

難道我做錯了什麼,導致無法被推回父視圖中的價值模型?

回答

0

您將不得不定義/使用observable屬性來使其雙向綁定,以便在視圖中進行的更改將反映在您的視圖模型中。

this.value = ko.observable('Test');適合您的要求。