I would like to end up with the following HTML in the DOM using jQuery and KnockoutJs templates:
<div class="messageToAndFromOtherMember" id="13">
<span>the message</span>
<span>2012-12-02 14:05:45.0</span>
</div>
I have started writing my KO template as follows:
<div class="messageToAndFromOtherMember" data-bind="attr:{ id: messageId}">
<span data-bind="text: message"></span>
<span data-bind="text: sendDateFmted"></span>
</div>
Upon a successful ajax request, the following js is executed:
var messageViewModel = {
message: response.message,
sendDateFmted: response.sendDateFmted,
messageId: response.messageId
};
ko.applyBindings(messageViewModel);
Now I am not sure how and where to actually do the binding: since my message does not exist before the ajax request is complete and I can have as several messages…
Can anyone please suggest a solution?
EDIT 1: I have added this to the html page:
<div data-bind="template: { name: 'message-template', data: messageViewModel }"></div>
I now get the following js error:
Uncaught Error: Unable to parse bindings. Message: ReferenceError:
$messageViewModel is not defined; Bindings value: template: { name:
‘message-template’, data: messageViewModel }
EDIT 2: I have altered my code as follows:
var messageViewModel = {
data: ko.observable({
message: response.message,
sendDateFmted: response.sendDateFmted,
messageId: response.messageId
})
};
$("<div>",{
class:"messageToAndFromOtherMember"
}).data("bind", "template: { name: 'message-template', data: data }").appendTo("#messagesToAndFromOtherMember");
ko.applyBindings(messageViewModel);
Please note that I am need to be able to add the element from jQuery in order to be able to add one message then another and so on. However, the above jQuery code does not work and I don’t see any such thing as data-bind in the DOM…
When the data arrives from the server:
With the mapping plugin, you could do something like this instead:
You really don’t need templates, if you are not going to use it in multiple places. It is simpler without templates. Look at http://jsfiddle.net/3BuHR/
If you are sure you need templates, here is an example: http://jsfiddle.net/Jxhm5/
You seem to be using knockout just for it’s templating functionality. KO can do much more.
I would instead let KO handle the DOM-creation based on
observableArray‘s. When the array is modified, the DOM will be updated automatically.And then when data arrives from the server:
KO will track insertions, deletions, reorderings, and update the DOM for you.
http://jsfiddle.net/v5sdf/