【问题标题】:knockout console log and observable undefined淘汰赛控制台日志和可观察到的未定义
【发布时间】:2012-06-11 16:48:09
【问题描述】:

我在控制台记录 observables 上看到了 cmets,但它似乎对我不起作用。此外,我的应用程序没有以我期望的默认 var 启动。 这两个问题放在一起是因为我怀疑它们在某种程度上是相关的。

Here is the fiddle.

HTML

<select data-bind="options: widgets, optionsText: 'name', value: current_widget, optionsCaption: 'Choose...'"></select>
<input data-bind="value: current_widget() ? current_widget().name : 'nothing'" />

Javascript

var cdta = {};
$(document).ready(function(){

    cdta.widgets_data = [{ "name": "foo", "id": "1"},{ "name": "bar", "id": "2"},{ "name": "bash", "id": "3"},{ "name": "baq","id": "4"}];

    cdta.local = {};
    cdta.local.current_widget = { "name": "foo", "id": "1"};

    alert('current_widget starting value should be: ' + cdta.local.current_widget.name);

    function app() {
        var self = this;

        //widgets
        self.widgets = ko.observableArray(cdta.widgets_data);

        // which widget to display from a local source
        alert('about to asign a current_widget named:' + cdta.local.current_widget.name);
        self.current_widget = ko.observable(cdta.local.current_widget);
    }
    ko.applyBindings(new app());

    alert('after applying bindings name of current widget: ' + current_widget().name);
    //expecting foo
    //but doesn’t alert because current_widget isnt defined
});

【问题讨论】:

  • @AlfeG 感谢您解决了变量问题
  • @Roman Bataev 也感谢关于 optionsCaption 的第 2 部分 - 这是一个真正的陷阱

标签: javascript knockout.js


【解决方案1】:

您的代码中有几个问题。

  1. current_widget 是 app 的一个属性,所以你需要做这样的事情

    var app = new app();
    ko.applyBindings(app);
    alert('after applying bindings name of current widget: ' + app.current_widget().name);
    
  2. 由于您使用 value 和 optionsCaption 竞价,knout 会将绑定到 value 的 observable 默认设置为 undefined。如果您删除 optionsCaption 绑定,它将起作用。如果您需要 optionsCaption 并且需要选择初始值,则必须在应用绑定后重置它:

    var app = new app();
    ko.applyBindings(app);
    app.current_widget(cdta.widgets_data[0]); //you have to select an object from the array, not a completely unrelated object cdta.local.current_widget
    alert('after applying bindings name of current widget: ' + app.current_widget().name);
    

更新: 我在#2上错了。您不必在应用绑定后重置值。真正的问题是您使用完全不相关的对象(不是来自数组)作为初始值。这将解决问题:

cdta.local.current_widget = cdta.widgets_data[0];

【讨论】:

    【解决方案2】:

    但是变量/方法current_widget确实是未定义的。 KnockoutJS 不会生成全局变量。

    如果您想在 viewModel 之外访问 viewModel 数据,那么您需要将其存储在某个地方(变量、窗口等)。

    var cdta = {};
    $(document).ready(function(){    
        //...    
        function app() {
           //...
        }
        window.app = new app();
        ko.applyBindings(window.app);
    
        alert('after applying bindings name of current widget: ' 
          + window.app.current_widget().name);
        //expecting foo
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2014-11-05
      • 2012-09-08
      • 2012-07-07
      • 2015-01-25
      • 2011-12-20
      • 1970-01-01
      相关资源
      最近更新 更多