使用knockout-classBindingProvider创建一个select

时间:2013-09-15 00:08:28

标签: javascript knockout.js

我正在使用可在此处找到的淘汰赛'插件':

https://github.com/rniemeyer/knockout-classBindingProvider

这是该工具的官方“演示”,其中添加了一个选择列表: http://jsfiddle.net/LvwRt/26/

这是Item对象,它有两个属性:

var Item = function(name) {
    this.id = ko.observable(name);
    this.name = ko.observable(name);
};

这个淘汰视图模型:

var ViewModel = function(items) {
    var self = this;

    this.editable = ko.observable(true);

    this.items = ko.observableArray(items);

    this.addItem = function() {
        self.items.push(new Item("New"));
    };

    this.deleteItem = function(item) {
        self.items.remove(item);
    };
};

ko.applyBindings(new ViewModel([
    new Item("Pen"),
    new Item("Pencil"),
    new Item("Eraser")
]), document.getElementById("content"));

select dom元素:

<select data-class="selectItem"></select>

selectItem绑定:

    selectItem: function(context) {
        return {
            options: context.$root.items, 
            value: name, 
            optionsText: 'name'
        }
    }

现在上面的代码正如您所期望的那样工作。 Knockout可以正确记录项目和所有内容。

但是,如果我将select绑定更改为

    selectItem: function(context) {
        return {
            options: context.$root.items, 
            value: id, 
            optionsText: 'name'
        }
    }

我收到以下错误:

Uncaught ReferenceError: id is not defined 

这是破损代码的链接。 http://jsfiddle.net/LvwRt/27/

1 个答案:

答案 0 :(得分:1)

id替换为this.id

return {
    options: context.$root.items, 
    value: this.id, 
    optionsText: 'name'
}

Demo