This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class window.CounterView extends Backbone.View | |
initialize: -> | |
@counter = new Counter() | |
el: $('#counter') | |
events: | |
'click button#inc-count' : 'inc' | |
'click button#dec-count' : 'dec' | |
render: -> | |
$(@el).find("#count").html "The count is " \ | |
+ @counter.get("count") | |
@ | |
inc: -> | |
ct = @counter.get("count") | |
@counter.set(count: ct+1) | |
@render() | |
dec: -> | |
ct = @counter.get("count") | |
@counter.set(count: ct-1) | |
@render() |
But what happens if we have a more complicated app and something else changes the Model?
Well as I said I'm just learning myself here, co the correct way that should be handled is to bind Model changes to the Views render function which looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class window.CounterView extends Backbone.View | |
initialize: -> | |
@counter = new Counter() | |
@counter.bind('change', @render) | |
el: $('#counter') | |
events: | |
'click button#inc-count' : 'inc' | |
'click button#dec-count' : 'dec' | |
render: => | |
$(@el).find("#count").html "The count is " \ | |
+ @counter.get("count") | |
@ | |
inc: -> | |
ct = @counter.get("count") | |
@counter.set(count: ct+1) | |
dec: -> | |
ct = @counter.get("count") | |
@counter.set(count: ct-1) |
Note the bind instruction which means that every time the counter changes, it calls the render function. You might also notice the fat arrow now on the render which make "this" still mean the View rather than the caller (which would be the Model otherwise.)
The explanation for all this is at http://jashkenas.github.com/coffee-script under "Function Binding".
Great & Useful Articles
ReplyDeleteBackbone.js Course | Backbone.js Training | Backbone.JS Online Course | Backbone.JS Training in Chennai