Problem with select in KnockoutJS and MooTools

2

I'm having a problem with a simple test with KnockoutJS in conjunction with MooTools:

<div>
    <select data-bind="foreach: animais">
        <option data-bind="text: nome, value: id"></option>
    </select>
</div>
var Animal = new Class({
    initialize: function(id, nome) {
        this.self = this;
        self.id = id;
        self.nome = nome;
    }
});

viewModel = new Class({
    initialize: function(animais) {
        this.self = this;
        self.animais = animais;
    }
});

ko.applyBindings(new viewModel([
    new Animal(1, "Cachorro"),
    new Animal(2, "Gato"),
    new Animal(3, "Macaco")
]));

Run JSFiddle: link

Interestingly, the select contains "Monkey" repeated 3 times.

    
asked by anonymous 14.09.2014 / 23:46

1 answer

3

The right thing to do is to use BindingHandler of options in select .

Your HTML would be smaller:

<div>
    <select data-bind="options: animais, optionsText: 'nome', optionsValue: 'id'" />
</div>

The parameters optionsText and optionsValue are respectively the properties of the object for the text and the value of option that will be generated.

Your JavaScript will be almost the same, except that this.self = this; was breaking the object's internal structure. With a little hit it is:

var Animal = new Class({
    initialize: function(id, nome) {
        var self = this;

        self.id = id;
        self.nome = nome;
    }
});

var viewModel = new Class({
    initialize: function(animais) {
        var self = this;
        self.animais = ko.observableArray(animais);
    }
});

ko.applyBindings(new viewModel([
    new Animal(1, "Cachorro"),
    new Animal(2, "Gato"),
    new Animal(3, "Macaco")
]));

Follow the JSFiddle with the example.

    
15.09.2014 / 00:18