【问题标题】:Creating a select with knockout-classBindingProvider使用 knockout-classBindingProvider 创建选择
【发布时间】:2013-09-19 09:35:00
【问题描述】:

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

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

选择 dom 元素:

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

selectItem 绑定:

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

现在上面的代码可以正常工作了。 Knockout 会跟踪项目并正确更新所有内容。

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

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

我收到以下错误:

Uncaught ReferenceError: id is not defined 

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

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    id替换为this.id

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

    Demo.

    【讨论】:

    • 其实它只是碰巧用了它:name 变量没有在这个函数中定义,所以它也应该是一个错误。但是 JSFiddle 被设置为带有执行结果的框架有一个名称('result')。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多