What are the advantages and disadvantages of the following 2 lines of code? I don't understand why there are 2 different ways to do the same thing.
this.listenTo(app.Todos, 'change:completed', this.filterOne); app.Todos.on('change:completed', this.filterOne);
Also when using .on, how do I determine is the default context?
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
Front-End MVC frameworks (Backbone, Angular, etc) all rely on a backend service to provide the data that, say Backbone, would then use as its model. You could have an entire MVC pattern on the backend that accepts requests and spits out some JSON for a frontend MVC framework to use.
Who uses Backbone. js? 3466 companies reportedly use Backbone. js in their tech stacks, including Uber, Pinterest, and reddit.
BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.
listenTo
is the newer and better option because these listeners will be automatically removed for you during stopListening
which is called when a view gets removed (via remove()
). Prior to listenTo
there was a really insidious problem with phantom views hanging around forever (leaking memory and causing misbehavior) because view methods were referenced as event listeners on models even though the view instances themselves were long gone and no longer in the DOM.
If you want to read the back story for listenTo
, search the backbone github repository for listenTo
and read through some of the longer issue discussions.
As to the default context, several things can end up bound to this
:
this.listenTo
, it will always be the view instance (pointed out by Wim Leers in the comments)this.listenTo
, the story gets complicated foo.on
), backbone will use that (thus this is a more robust approach)function () {//your event handler}.bind(this)
, you can also manually control the context (also recommended)_.bind
or $.proxy
are available alternatives to ECMA function.bind
this.bindAll('onClick', ...)
will ensure the view instance is the this
context when any view methods are used as event handlersevents
property will get bound for you automatically to the view instance by backbone (this is belt & suspenders with bindAll
)So to summarize into some guidelines:
events
property whenever possible as it is concise and correctthis.listenTo
for all bindings to models and collectionsFunction.bind
because hey, standards, but there are several good options here.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With