通过KnockbackJS访问骨干模型的骨干集合中的数据



在过去的几天里,我一直在玩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

中的示例

我无法获得集合中模型内部的数据。有什么线索、提示、提示吗?

我明白了,这是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>

Thanks to this SO post

相关内容

  • 没有找到相关文章

最新更新