Its all about the version
last week I downloaded couple of good frameworks I am going to use more and more for the client side:
- CoffeeScript – I was skeptic at start, but I am addicted now
- KnockOutJS – MVVM, its all about two way binding
- BackBone – MVC, utilities and good app design
- KnockBack – takes the good of KnockOutJS & BackBone and combine them together
I started to write a simple code that will show list of items (Customer name and severity) and allow the user to double click on the customer name / Severity text so that it will become editable
It took me 10 min to write it and 4 hours to debug why it was not working
CoffeeScript code:
TicketViewModel = (ticket) ->
@customer_name = kb.observable(ticket, {key: 'CustomerName', write: ((text) -> ticket.save({CustomerName: text}))}, this)
@editingCustomerName = ko.observable(false)
@editCustomerName = (event) => @editingCustomerName(true)
@severity = kb.observable(ticket, {key: 'Severity', write: ((text) -> ticket.save({Severity: text}))}, this)
@editingSeverity = ko.observable(false)
@editSeverity = (event) => @editingSeverity(true)
@destroyTodo = => model.destroy()
@
TicketListViewModel = (tickets) ->
@tickets = ko.observableArray([])
@collection_observable = kb.collectionObservable(tickets, @tickets, { view_model_constructor: TicketViewModel })
@removeTicket = (ticket) =>
@tickets.remove(ticket)
@
@
app_view_model =
tickets_list: new TicketListViewModel(tickets)
HTML:
<ul class="ticket-list" data-bind="foreach: tickets_list.tickets">
<li>
<div class="ticket">
<span class="ticket-customer" data-bind="text: customer_name, visible: !editingCustomerName(), dblclick: editCustomerName"></span>
<input data-bind="value: customer_name, visible: editingCustomerName, hasfocus: editingCustomerName" />
<span class="ticket-severity" data-bind="text: severity, visible: !editingSeverity(), dblclick: editSeverity"></span>
<select data-bind="value: severity, visible: editingSeverity, hasfocus: editingSeverity">
<option value="P1">P1</option>
<option value="P2">P2</option>
<option value="P3">P3</option>
</select>
<a href="#" data-bind="click: $parent.removeTicket">Delete me</a>
</div>
</li>
</ul>
I had two problems:
- The click event was not binded to my function on my model
- After fixing it, When clicking the function didn’t get as first parameter the current item
to make a long story short I had two key problems
- The context I was looping on was the root rather than the collection, so I had to specifically write the function name with its parent , so instead of “$parent.removeTicket” I had to write “$root.tickets_list.removeTicket”
- the version of KnockoutJS that is delivered with KnockBack is OLD! and didn’t have support of passing the current item
I need to find a better way to share code…. any suggestions?
Its all about the version
Reviewed by Ran Davidovitz
on
1:34 PM
Rating:
No comments:
Post a Comment