Common Backbone.js Utilities
Thanks go out to the following entities for contributing financially to support the growth of this project:
Licensed under the incredibly permissive MIT License
Copyright © 2013+ Bevry Pty Ltd
Thanks go out to the following entities for contributing financially to support the growth of this project:
Licensed under the incredibly permissive MIT License
Copyright © 2013+ Bevry Pty Ltd
# Import | |
Backbone = require('backbone') | |
{QueryCollection} = require('query-engine') | |
{BackboneNestyModel} = require('backbone-nesty') | |
# Model | |
Model = BackboneNestyModel | |
# View | |
class View extends Backbone.View | |
fieldMap: null | |
subViewMap: null | |
subViews: null | |
constructor: -> | |
@fieldMap ?= {} | |
@subViewMap ?= {} | |
@subViews ?= {} | |
super | |
setValues: (fieldValues) -> | |
# Check | |
return @ unless @fieldMap? | |
# Fetch | |
for own key,value of fieldValues | |
klass = @fieldMap[key] | |
@$el.find(":input.#{klass}").val(value) | |
# Chain | |
@ | |
getValues: -> | |
# Fetch | |
values = {} | |
for own key,klass of @fieldMap | |
values[key] = @$el.find(":input.#{klass}").val() | |
# Return | |
return values | |
render: ($parent) -> | |
# Render sub views | |
for own key,klass of @subViewMap | |
$subView = @$el.find(".#{klass}") | |
@subViews[key].render($subView) | |
# Attach | |
$parent?.append(@$el) | |
# Chain | |
@ | |
# Collection | |
class Collection extends QueryCollection | |
model: Model | |
# Export | |
module.exports = { | |
Model | |
Collection | |
View | |
} |
# Add emit to backbone | |
Backbone.Model::emit = | |
Backbone.View::emit = | |
Backbone.Events.emit = Backbone.Events.trigger | |
# Add emit to jQuery | |
$.fn.emit = $.fn.trigger |
# Request | |
request: (resource,data,next) -> | |
# Socket | |
if @transport is 'socket' | |
# Prepare | |
if @socket? is false | |
@socket = io.connect() | |
@socket.on 'connect', => | |
@request(resource, data, next) | |
# Request | |
else | |
@socket.emit(resource, data, next) | |
# AJAX | |
else if @transport is 'ajax' | |
$.ajax({ | |
url: '/'+resource | |
data: data | |
type: 'POST' | |
success: (data, testStatus, jqXHR) -> | |
if data.error | |
next(data.error,data) | |
else | |
next(null,data) | |
error: (jqXHR, textStatus, err) -> | |
next(err) | |
}) | |
# Unknown | |
else | |
err = new Error('Unknown transport') | |
next(err) | |
# Chain | |
@ |