多视图模型绑定错误:knockout js

时间:2012-12-24 07:09:18

标签: knockout.js

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

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


        });

如何解决,“此”问题

1 个答案:

答案 0 :(得分:1)

“this”视图模型

使用另一个变量
var self = this; 

并使用self的{​​{1}}变量实例 此外,您可以为每个型号使用this 这里你的代码是可行的 You code