0

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

    <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]); 


        });

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

4

1 回答 1

1

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

var self = this; 

并使用self变量 instadethis
也可以data-bind="with : viewModel"用于每个模型。
在这里你的代码是可行的 你的代码

于 2012-12-24T09:33:19.113 回答