过去几天我一直在玩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>
我无法访问集合中模型的数据。任何线索,提示,提示?
答案 0 :(得分: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>