0

这几天我在玩 Knockout 和 Backbone,遇到了 KnockbackJS 框架,它结合了 Knockout 的绑定能力和 Backbone 的数据建模魔法。

在这个简单的示例中,我有一个 Backbone 模型的 Backbone 集合,并且在将它们绑定到我的 HTML 时遇到了问题。

这是我的 JavaScript:

var Model = Backbone.Model.extend({
    defaults: {
        firstName: "",
        lastName: ""

    }
});



var Collection = Backbone.Collection.extend({
    data : Model
});


var temp1 = new Model({firstName: "aaa", lastName:"bbb"});
console.log("new model");

var temp2 = new Model({firstName: "BBB", lastName:"CCCC"});
console.log("newest model");


var collection = new Collection([temp1, temp2]);

//---------Knockout/Backbone bridge---------

var view_model = kb.viewModel(collection, { read_only: true });

ko.applyBindings(view_model);

...和我的简单 HTML:

<div data-bind="foreach: data">
   <span data-bind="text: name"></span>
   <span data-bind="text: artist"></span>
</div>

JSfiddle 中的这个例子

我无法获取集合中模型内部的数据。任何线索,提示,提示?

4

1 回答 1

0

我明白了,这是JS代码:

console.clear();
var PersonModel = Backbone.Model.extend();


var model1 = new PersonModel({firstName: "aaa", lastName:"bbb"});
var model2 = new PersonModel({firstName: "CCCC", lastName:"DDDD"});

var PersonViewModel = function (person) {

    this.firstName = kb.observable(person, 'firstName');
    this.lastName = kb.observable(person, 'lastName');
    this.fullName = ko.computed((function () {
        return "" + (this.firstName()) + " " + (this.lastName());
    }), this);
};

var PersonsModel = Backbone.Collection.extend({ model: PersonModel});
var personsModel = new PersonsModel([model1,model2]);

var PersonsViewModel = function (persons) {
    this.persons = kb.collectionObservable(persons);
};

var personsViewModel = new PersonsViewModel(personsModel);

ko.applyBindings(personsViewModel, $('#kb_collection_observable')[0]);

...这是 HTML:

<div id="kb_collection_observable">
                <div data-bind="if: persons">
                    <span>Data </span>
                </div>
                <div data-bind="foreach: persons">
                    <p>First name: <input class='text' data-bind="value: firstName" /></p>
                    <p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
                </div>
</div>

感谢这篇 SO 帖子

于 2013-05-09T11:46:27.870 回答