0

I was playing around with Knockout and Backbone these past few days and came across the KnockbackJS framework which sort of combines the binding powers of Knockout with data modeling magic of Backbone.

In this simple example I have a Backbone collection of Backbone models and I'm having problems binding them to my HTML.

This is my 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);

...and my simple HTML:

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

This example in JSfiddle

I can't get to the data inside of a model in a collection. Any clues, hints, tips?

sikac
  • 56
  • 1
  • 4

1 Answers1

0

I've got it, here is the JS code:

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

...and here is the 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

Community
  • 1
  • 1
sikac
  • 56
  • 1
  • 4