[英]Knockout Component Not Binding View Model (ES6)
我確定我在這里完全看不到什么東西,但是我是第一次嘗試ES6,在無所事事的五天之后,我想我應該向社區開放。
我有一個視圖模型類:
class TestViewModel
{
constructor(params)
{
this.firstName = ko.observable(params.firstName);
this.message = ko.computed(function() { return 'Hello, ' + this.firstName() + '!' }, this);
}
}
export default { viewModel: TestViewModel, template: templateMarkup };
(忽略模板,它只是使用導入的段落標簽)
然后有一個入口點:
"use strict";
import $ from 'jquery';
import ko from 'knockout';
import comp from '../test-model/test-model';
ko.components.register("test-model", {
viewModel: comp.viewModel,
template: comp.template
});
let m = new comp.viewModel({ firstName: "world" });
$("document").ready(function() {
ko.applyBindings(m);
});
我的頁面有一個簡單的組件:
<test-component></test-component>
當我查看頁面時,該元素包含我組件的模板。 該頁面沒有顯示消息“ Hello,world!”,而是顯示“ Hello,undefined!”。 我已經多次調試了該過程,並且它總是成功地創建帶有適當參數的TestViewModel實例。 但是綁定到頁面的視圖模型是由Knockout中的createViewModel函數生成的。 我將模型實例綁定到組件的設置中缺少什么?
您正在混合組件和根視圖模型。 您的構造函數將被調用兩次:
new
自己就在let m...
線; 相反,您需要這樣的東西:
"use strict"; class TestViewModel { constructor(params) { this.firstName = ko.observable(params.firstName); this.message = ko.computed(() => 'Hello, ' + this.firstName() + '!'); } } var templateMarkup = "<p data-bind='text: message'></p>"; var comp = { viewModel: TestViewModel, template: templateMarkup }; ko.components.register("test-component", { viewModel: comp.viewModel, template: comp.template }); $("document").ready(function() { ko.applyBindings({}); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <test-component params="firstName: 'world'"></test-component>
這似乎可行 ,但我仍然建議對此謹慎。 ko.components
的viewModel
條目稱為構造函數,而我個人不知道構造函數和ES6類之間的細微差別。 根據文檔,您可以放心使用它,並改用自定義視圖模型工廠:
ko.components.register("test-component", {
viewModel: { createViewModel: (params, componentInfo) => new comp.viewModel(params) },
template: comp.template
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.