【问题标题】:Multiple view model binding error: knocout js多视图模型绑定错误:淘汰js
【发布时间】:2012-12-24 17:48:39
【问题描述】:

我只是想摆弄淘汰赛提供的样本并尝试绑定两个视图模型,这是代码,第二个视图模型有问题:

    <div class='liveExample1'>   
      <p>First name: <input data-bind='value: firstName' /></p> 
      <p>Last name: <input data-bind='value: lastName' /></p> 
      <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>  
   </div>

    <div class='liveExample'> 

    <form data-bind="submit: addItem">
        New item:
        <input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
        <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
        <p>Your items:</p>
        <select multiple="multiple" width="50" data-bind="options: items"> </select>
    </form>

    </div>

我的视图模型是:

    <script type="text/javascript">
        // Here's my data model
        $(document).ready(function () {
            var ViewModel = function (first, last) {
                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);

                this.fullName = ko.computed(function () {
                    // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
                    return this.firstName() + " " + this.lastName();
                }, this);
            };


            ko.applyBindings(new ViewModel("Planet", "Earth"), $("#liveExample1")[0]); // This makes Knockout get to work?



    var SimpleListModel = function(items) {
        this.items = ko.observableArray(items);
        this.itemToAdd = ko.observable("");
        this.addItem = function() {
            if (this.itemToAdd() != "") {
                this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
                this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
            }
        }.bind(this);  // Ensure that "this" is always this view model
    };

    ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"]), $("#liveExample")[0]); 


        });

我该如何解决,“这个”问题

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    “this”视图模型使用另一个变量

    var self = this; 
    

    并使用self 变量替代this
    您也可以为每个模型使用data-bind="with : viewModel"
    在这里你的代码是可行的 You code

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 2013-01-14
      相关资源
      最近更新 更多