Better Backbone Applications With Marionettejs - Ebook download as PDF File . pdf), Text File .txt) or read book online. osakeya.info1 is a growing library that. introduction to building scalable applications with osakeya.info Better ³http:// osakeya.info .. Of course, we'll see that there's a much better way to manage views in Marionette. osakeya.info to your will, so that your web apps remain sub-optimal modifications had to be implemented in order to provide a better learning.
|Language:||English, Spanish, Japanese|
|Distribution:||Free* [*Registration Required]|
Instead, views listen to the model "change" events, and react or re-render themselves appropriately. Collections A Collection helps you deal with a group of related models, handling the loading and saving of new models to the server and providing helper functions for performing aggregations or computations against a list of models.
Aside from their own events, collections also proxy through all of the events that occur to models within them, allowing you to listen in one place for any change that might happen to any model in the collection. However, it's fairly common to encounter APIs that return data in a different format than what Backbone expects. If you're strict about not allowing views to reach outside of themselves, it helps keep your interface flexible — allowing views to be rendered in isolation in any place where they might be needed.
Backbone remains unopinionated about the process used to render View objects and their subviews into UI: you define how your models get translated into HTML or SVG, or Canvas, or something even more exotic. Some basic approaches to rendering views can be found in the Backbone primer. Routing with URLs In rich web applications, we still want to provide linkable, bookmarkable, and shareable URLs to meaningful locations within an app. Use the Router to update the browser URL whenever the user reaches a new "place" in your app that they might want to bookmark or share.
Conversely, the Router detects changes to the URL — say, pressing the "Back" button — and can tell your application exactly where you are now.
Events Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments.
Events ; object. Events onobject. The callback will be invoked whenever the event is fired. If you have a large number of different events on a page, the convention is to use colons to namespace them: "poll:start", or "change:selection".
The event string may also be a space-delimited list of several events For example, to proxy all events from one object to another: proxy. If no context is specified, all of the versions of the callback with different contexts will be removed. If no callback is specified, all callbacks for the event will be removed.
If no event is specified, callbacks for all events will be removed. Subsequent arguments to trigger will be passed along to the event callbacks. Handy for saying "the next time that X happens, do this". When multiple events are passed in using the space separated syntax, the event will fire once for every event you passed in, not once for a combination of all events listenToobject. The advantage of using this form, instead of other. The callback will always be called with object as context.
Either call stopListening with no arguments to have the object remove all of its registered callbacks Catalog of Events Here's the complete list of built-in Backbone events, with arguments. You're also free to trigger your own events on Models, Collections and Views as you see fit. The Backbone object itself mixes in Events, and can be used to emit any global events that your application needs.
Generally speaking, when calling a function that emits an event model. Note that this is rarely, perhaps even never, a good idea.
You extend Backbone. Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes. The following is a contrived example, but it demonstrates defining a model with a custom method, setting an attribute, and firing an event keyed to changes in that specific attribute. After running this code once, sidebar will be available in your browser's console, so you can play around with it. Model and provide instance properties, as well as optional classProperties to be attached directly to the constructor function.
If you define a preinitialize method, it will be invoked when the Model is first created, before any instantiation logic is run for the Model. If you define an initialize function, it will be invoked when the model is created.
The model. Note that the reverse is not true, as passing this option to the constructor will not automatically add the model to the collection. Useful, sometimes. For example: note. If any of the attributes change the model's state, a "change" event will be triggered on the model. Change events for specific attributes are also triggered, and you can bind to those as well, for example: change:title, and change:content.
You may also pass individual keys and values.
Fires a "change" event unless silent is passed as an option. If you set the id in the attributes hash, it will be copied onto the model as a direct property. Models can be retrieved by id from collections, and the id is used to generate model URLs by default. This is at odds with the traditional approach to web app development which is very server-centric, requiring a complete page reload to move from one page to the next.
In addition to resulting in a great deal of duplicated content being served back to the user, this approach affects both latency and the general responsiveness of the user experience. A trend to improve perceived latency in the past few years has been to move towards building Single Page Applications SPAs - apps which after an initial page load are able to handle subsequent navigations and requests for data without the need for a complete reload.
These URLs also make it possible to bookmark and share a particular application state, without the need to navigate to completely new pages. The typical SPA consists of smaller pieces of interface representing logical entities, all of which have their own UI, business logic and data.
A good example is a basket in a shopping web application which can have items added to it. This basket might be presented to the user in a box in the top right corner of the page see the picture below : The basket and its data are presented in HTML.
There was a time when we used jQuery or a similar DOM manipulation library and a bunch of Ajax calls and callbacks to keep the two in sync. That often produced code that was not well-structured or easy to maintain.
Bugs were frequent and perhaps even unavoidable. The need for fast, complex, and responsive Ajax-powered web applications demands replication of a lot of this logic on the client side, dramatically increasing the size and complexity of the code residing there. Eventually this has brought us to the point where we need MVC or a similar architecture implemented on the client side to better structure the code and make it easier to maintain and further extend during the application life-cycle.
Model and simply defines default values for two data attributes. As you will discover in the upcoming chapters, Backbone Models provide many more features but this simple Model illustrates that first and foremost a Model is a data container.
View and is instantiated with an associated Model. In our example, the render method uses a template to construct the HTML for the Todo item which is placed inside an li element. Each call to render will replace the content of the li element using the current Model data. Thus, a View instance renders the content of a DOM element using the attributes of an associated Model. Later we will see how a View can bind its render method to Model change events, causing the View to re-render whenever the Model changes.
So far, we have seen that Backbone. View implements the View. However, as we noted earlier, Backbone departs from traditional MVC when it comes to Controllers - there is no Backbone. Instead, the Controller responsibility is addressed within the View. Recall that Controllers respond to requests and perform appropriate actions which may result in changes to the Model and updates to the View.
In a single-page application, rather than having requests in the traditional sense, we have events. Events can be traditional browser DOM events e. While in this instance events help us relate Backbone to the MVC pattern, we will see them playing a much larger role in our SPA applications.
Event is a fundamental Backbone component which is mixed into both Backbone. Model and Backbone. View, providing them with rich event management capabilities.
Note that the traditional controller role Smalltalk style is performed by the template, not by the Backbone. This completes our first encounter with Backbone. The remainder of this book will explore the many features which build on these simple constructs. Once loaded, a client-side Router intercepts URLs and invokes client-side logic in place of sending a new request to the server.
The handlers update the DOM and Models, which may trigger additional events. Models are synced with Data Sources which may involve communicating with back-end servers. Models The built-in capabilities of Models vary across frameworks. When using Models in real-world applications we generally also need a way of persisting Models. A Model may have multiple Views observing it for changes. By observing we mean that a View has registered an interest in being informed whenever an update is made to the Model.
This allows the View to ensure that what is displayed on screen is kept in sync with the data contained in the model. Depending on your requirements, you might create a single View displaying all Model attributes, or create separate Views displaying different attributes.
In Backbone, these groups are called Collections. Managing Models in groups allows us to write application logic based on notifications from the group when a Model within the group changes. This avoids the need to manually observe individual Model instances. Collections are also useful for performing any aggregate computations across more than one model. Views Users interact with Views, which usually means reading and editing Model data. For example, in our Todo application, Todo Model viewing happens in the user interface in the list of all Todo items.
We then add our render callback as a Model subscriber, so the View can be triggered to update when the Model changes. You may wonder where user interaction comes into play here. A Controller makes this decision. It has long been considered bad practice and computationally expensive to manually create large blocks of HTML markup in-memory through string concatenation.
The grunt work of populating templates with data is generally taken care of by the framework itself. This has several benefits, particularly when opting to store templates externally which enables applications to load templates dynamically on an as-needed basis.
So does Backbone. Not really. What does MVC give us? To summarize, the MVC pattern helps you keep your application logic separate from your user interface, making it easier to change and maintain both.
Thanks to this separation of logic, it is more clear where changes to your data, interface, or business logic need to be made and for what your unit tests should be written. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. The observer-viewer nature of this relationship is what facilitates multiple Views being attached to the same Model.
For developers interested in knowing more about the decoupled nature of MVC once again, depending on the implementation , one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and Controllers have a slightly different relationship. Summary Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application.
Its workspace uses Backbone to create task views, activities, accounts, tags and more. Walmart Mobile Walmart chose Backbone to power its mobile web applications, creating two new extension frameworks in the process - Thorax and Lumbar.
Airbnb Airbnb developed its mobile web app using Backbone and now uses it across many of its products. This boilerplate can be reused in many ways with little to no alteration and will allow you to run code from examples with ease.
Models can be created by extending Backbone. Default values There are times when you want your model to have a set of default values e. This can be set using a property called defaults in your model.