Created
May 28, 2013 10:31
-
-
Save meleyal/5661870 to your computer and use it in GitHub Desktop.
Backbone.PluginView latest
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
### | |
Backbone.PluginView | |
https://github.com/meleyal/backbone.pluginview | |
Copyright (c) 2012 William Meleyal | |
MIT License | |
Make jQuery plugins from your Backbone Views. | |
Backbone.PluginView extends Backbone.View with some simple helpers for creating jQuery plugins ($.fn). | |
This enables creating Backbone.View instances with jQuery syntax: | |
`$('.example').myView([options]);` | |
### | |
class Backbone.PluginView extends Backbone.View | |
# Add the plugin to the jQuery.fn namespace. | |
# This enables instantiating new views by calling `$(element).myView()` | |
@exportPlugin: (namespace) -> | |
klass = this | |
$.fn[namespace] = (options = {}) -> | |
@each (idx, el) -> klass.install el, options, namespace | |
# Install the plugin | |
# Follows the standard jQuery plugin spec: | |
# http://docs.jquery.com/Plugins/Authoring | |
# - Create a new instance of the View class | |
# - Store a reference to the plugin instance in `$el.data` | |
# - Return the instance if it was already installed | |
# - If a string is passed, attempt to call a method by that name | |
# - Bind an event handler to remove the view if the event has been defined | |
# - NOTE: we use `on` instead of `one` so we can unbind the event in case the view is removed manually. | |
@install: (el, options, namespace) -> | |
klass = this | |
if instance = $(el).data namespace | |
if options and typeof options is 'string' | |
instance[options].call klass | |
else | |
return instance | |
else | |
options = _.extend options, { el } | |
instance = new klass options | |
$(el).data namespace, instance | |
@removeEvent = Backbone.PluginView.removeEvent | |
$(document).on(@removeEvent, instance.remove) if @removeEvent | |
# Ensure each view instance has a remove method and unbind our removeEvent handler. | |
# Delegate to `View.remove()`: http://backbonejs.org/#View-remove | |
remove: => | |
$(document).off @removeEvent, @remove | |
super |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment