I'm a little puzzled by some code I plunked together that doesn't behave quite as I'd expect.
I'm sure I'm doing something wrong (and given the late hour here, it might be something simple), but I'm looking for some clarity on why this happens.
I'm using:
- jQuery 1.10.2
- Knockout 2.3.0
- Bootstrap 3.0.3
The Problem
- I define a function in my ViewModel, which sets an observable to a certain value.
- This is not called from anywhere else in my code.
- I define a
data-bind="click: AddAnnouncement"
binding on a button that's part of a button group. - When
ko.applyBindings(vm)
is called, theAddAnnouncement
function fires, giving me an undesired result long before I click on anything.
The Code in Question
Can be found in a JSFiddle at: http://jsfiddle.net/SeanKilleen/v8ReS/.
Essentially, I have the following JavaScript code:
var MyNamespace = MyNamespace || {
ViewModel: function(){
'use strict';
var self = this;
self.AddingAnnouncement = ko.observable(false);
self.AddAnnouncement = function(){
self.AddingAnnouncement(true);
};
self.Start = function(){
self.AddingAnnouncement(false);
};
self.Start();
}
};
var vm;
$(document).ready(function(){
'use strict';
vm = new MyNamespace.ViewModel();
ko.applyBindings(vm);
//do something with jQuery? Bind a VM?
});
My binding code is also pretty elementary (I thought):
<div class="container">
<div class="row">
<div class="btn-group">
<button type="button" class="btn btn-default"><abbr Title="Announcement" data-bind="click: AddAnnouncement()">A</abbr>
</button>
</div>
</div>
<div class="row" data-bind="visible: AddingAnnouncement() == true">
<h1>Add a new announcement</h1>
</div>
</div>
What I think it's doing
I think the code in question is doing the following:
- Defining a namespace called
MyNamespace
(albeit probably not in the best way; this may be part of the problem?) - Defining a
ViewModel
object inside the namespace - Giving the
ViewModel
object an observable calledAddingAnnouncment
and a function calledAddAnnouncement
, which setsAddingAnnouncement
to true. - Defines a
Start
method which ensures thatAddingAnnouncement
is set to false by default; - Calls the
Start
method as the last step in its initialization.
What am I Missing Here?
I think I'm not grasping some standard behavior of JavaScript or something about the way knockout binds models, but it seems like when applying the bindings, knockout executes all of the functions, even for the click bindings. However, that doesn't make sense to me and so I'm betting I'm wrong.
Someone enlighten me? Thanks!