Reputation: 1518
I'm trying to teach myself KnockoutJs, and I thought a simple image gallery page would be a good way to increase complexity a little. Unfortunately, I'm already hitting problems that I can't seem to figure out.
My template looks like this:
<div>
<img data-bind="attr: { alt: selectedImage.description, src: selectedImage.sourceUrl }">
</div>
<div data-bind="foreach: images">
<img data-bind="attr: { alt: description, src: sourceUrl }, event: { click: onClick }">
</div>
Which should be simple enough. Then I have my script with some dummy data:
(function ($, ko) {
'use strict';
function ViewModel() {
var self = this;
self.images = [
new ImageViewModel(self, { description: 'some image alt', sourceUrl: '/someimage.jpg' }),
new ImageViewModel(self, { description: 'description two', sourceUrl: '/someotherimage.jpg' })
];
self.selectedImage = ko.observable(self.images[0]);
return self;
}
function ImageViewModel(gallery, image) {
var self = this;
self.description = ko.observable(image.description);
self.sourceUrl = ko.observable(image.sourceUrl);
self.onClick = function (data, event) {
gallery.selectedImage(data);
};
return self;
}
ko.applyBindings(new ViewModel());
})(jQuery, ko);
My problem is that the selectedImage
binding never works. It doesn't work initially, and it doesn't work when I click one of the thumbnails. It always renders the same:
<div>
<img data-bind="attr: { alt: selectedImage.description, src: selectedImage.sourceUrl }">
</div>
<div data-bind="foreach: images">
<img src="/someimage.jpg" alt="some image alt" data-bind="attr: { alt: description, src: sourceUrl }, event: { click: onClick }">
<img src="/someotherimage.jpg" alt="description two" data-bind="attr: { alt: description, src: sourceUrl }, event: { click: onClick }">
</div>
I'm sure it's something simple, but I've been banging my head against the wall trying to figure out what's wrong. There's no error in the console or anything. The foreach
binding works fine, but the selectedImage.*
bindings don't.
What am I missing here?
Upvotes: 0
Views: 1395
Reputation: 1587
Your selectedImage variable is an observable, and observables are functions. Thus you forgot to use the parenthesis here. ;)
<img data-bind="attr: { alt: selectedImage.description, src: selectedImage.sourceUrl }">
It should be.
<img data-bind="attr: { alt: selectedImage().description, src: selectedImage().sourceUrl }">
Or if you want to get rid of the parenthesis use the "with" binding. http://knockoutjs.com/documentation/with-binding.html
Upvotes: 3