Create Backbone.Views via jQuery.
Backbone.Widget extends Backbone.View with some simple helpers for creating jQuery widgets/plugins ($.fn).
This enables creating Backbone.View instances with jQuery syntax:
$('.example').myView([options]);At the code level Backbone.View offers a nice way to structure your jQuery widget/plugin code.
Backbone.Widget just provides some minimal glue code to make this easy.
At the application / architecture level, the JS Widgets approach can offer a hybrid / DOM-centric alternative to single page apps; with static HTML from the server providing the foundation for multiple mini-applications (widgets).
// extend Backbone.Widget
MyView = Backbone.Widget.extend({
initialize: function(options) {
console.log(this.el, options);
}
});
// export as widget
MyView.exportWidget('myView');
// call on element
$('.example').myView([options]);# extend Backbone.Widget
class MyView extends Backbone.Widget
# export as widget
@exportWidget 'myView'
initialize: (options) ->
console.log @el, options
# call on element
$('.example').myView([options])View methods can be called directly on the element
$('.example').myView('remove')A reference to the view instance is stored in the element's $.data.
view = $('.example').data('myView');
console.log(view.cid); // view0The namespace option is passed to the view instance for convenience.
This can be useful for e.g. namespacing events.
...
initialize: function(options) {
console.log(options.namespace); // myView
}
...Widgets's can optionally remove themselves on a given event.
This can be useful with pjax / turbolinks
where you need to routinely cleanup views between "page loads".
See the wiki page for more details.