repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var behaviorEvents = _.result(this, 'events'); var viewEvents = this.view.events; if (!viewEvents) { if (!behaviorEvents) { return; } else { viewEvents = {}; } } var namespacedEvents = this.__namespaceEvents(behaviorEvents); var boundBehaviorEvents = this.__bindEventCallbacksToBehavior(namespacedEvents); if (_.isFunction(viewEvents)) { this.view.events = _.wrap(_.bind(viewEvents, this.view), function(viewEventFunction) { return _.extend(boundBehaviorEvents, viewEventFunction()); }); } else if (_.isObject(viewEvents)) { this.view.events = _.extend(boundBehaviorEvents, viewEvents); } }
javascript
function() { var behaviorEvents = _.result(this, 'events'); var viewEvents = this.view.events; if (!viewEvents) { if (!behaviorEvents) { return; } else { viewEvents = {}; } } var namespacedEvents = this.__namespaceEvents(behaviorEvents); var boundBehaviorEvents = this.__bindEventCallbacksToBehavior(namespacedEvents); if (_.isFunction(viewEvents)) { this.view.events = _.wrap(_.bind(viewEvents, this.view), function(viewEventFunction) { return _.extend(boundBehaviorEvents, viewEventFunction()); }); } else if (_.isObject(viewEvents)) { this.view.events = _.extend(boundBehaviorEvents, viewEvents); } }
[ "function", "(", ")", "{", "var", "behaviorEvents", "=", "_", ".", "result", "(", "this", ",", "'events'", ")", ";", "var", "viewEvents", "=", "this", ".", "view", ".", "events", ";", "if", "(", "!", "viewEvents", ")", "{", "if", "(", "!", "behaviorEvents", ")", "{", "return", ";", "}", "else", "{", "viewEvents", "=", "{", "}", ";", "}", "}", "var", "namespacedEvents", "=", "this", ".", "__namespaceEvents", "(", "behaviorEvents", ")", ";", "var", "boundBehaviorEvents", "=", "this", ".", "__bindEventCallbacksToBehavior", "(", "namespacedEvents", ")", ";", "if", "(", "_", ".", "isFunction", "(", "viewEvents", ")", ")", "{", "this", ".", "view", ".", "events", "=", "_", ".", "wrap", "(", "_", ".", "bind", "(", "viewEvents", ",", "this", ".", "view", ")", ",", "function", "(", "viewEventFunction", ")", "{", "return", "_", ".", "extend", "(", "boundBehaviorEvents", ",", "viewEventFunction", "(", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "viewEvents", ")", ")", "{", "this", ".", "view", ".", "events", "=", "_", ".", "extend", "(", "boundBehaviorEvents", ",", "viewEvents", ")", ";", "}", "}" ]
Adds behavior's event handlers to view Behavior's event handlers fire on view events but are run in the context of the behavior @method __bindEventCallbacks @private
[ "Adds", "behavior", "s", "event", "handlers", "to", "view", "Behavior", "s", "event", "handlers", "fire", "on", "view", "events", "but", "are", "run", "in", "the", "context", "of", "the", "behavior" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L1933-L1955
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(eventHash) { // coped from Backbone var delegateEventSplitter = /^(\S+)\s*(.*)$/; var namespacedEvents = {}; var behaviorId = this.cid; _.each(eventHash, function(value, key) { var splitEventKey = key.match(delegateEventSplitter); var eventName = splitEventKey[1]; var selector = splitEventKey[2]; var namespacedEventName = eventName + '.behavior.' + behaviorId; namespacedEvents[[namespacedEventName, selector].join(' ')] = value; }); return namespacedEvents; }
javascript
function(eventHash) { // coped from Backbone var delegateEventSplitter = /^(\S+)\s*(.*)$/; var namespacedEvents = {}; var behaviorId = this.cid; _.each(eventHash, function(value, key) { var splitEventKey = key.match(delegateEventSplitter); var eventName = splitEventKey[1]; var selector = splitEventKey[2]; var namespacedEventName = eventName + '.behavior.' + behaviorId; namespacedEvents[[namespacedEventName, selector].join(' ')] = value; }); return namespacedEvents; }
[ "function", "(", "eventHash", ")", "{", "// coped from Backbone", "var", "delegateEventSplitter", "=", "/", "^(\\S+)\\s*(.*)$", "/", ";", "var", "namespacedEvents", "=", "{", "}", ";", "var", "behaviorId", "=", "this", ".", "cid", ";", "_", ".", "each", "(", "eventHash", ",", "function", "(", "value", ",", "key", ")", "{", "var", "splitEventKey", "=", "key", ".", "match", "(", "delegateEventSplitter", ")", ";", "var", "eventName", "=", "splitEventKey", "[", "1", "]", ";", "var", "selector", "=", "splitEventKey", "[", "2", "]", ";", "var", "namespacedEventName", "=", "eventName", "+", "'.behavior.'", "+", "behaviorId", ";", "namespacedEvents", "[", "[", "namespacedEventName", ",", "selector", "]", ".", "join", "(", "' '", ")", "]", "=", "value", ";", "}", ")", ";", "return", "namespacedEvents", ";", "}" ]
Namespaces events in event hash @method __namespaceEvents @param eventHash {Object} to namespace @return {Object} with event namespaced with '.behavior' and the cid of the behavior @private
[ "Namespaces", "events", "in", "event", "hash" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L1965-L1978
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(name) { if (name === 'change' || name.indexOf('change:') === 0) { View.prototype.trigger.apply(this.view, arguments); } if (name.indexOf('change:hide:') === 0) { this.view.render(); } NestedCell.prototype.trigger.apply(this, arguments); }
javascript
function(name) { if (name === 'change' || name.indexOf('change:') === 0) { View.prototype.trigger.apply(this.view, arguments); } if (name.indexOf('change:hide:') === 0) { this.view.render(); } NestedCell.prototype.trigger.apply(this, arguments); }
[ "function", "(", "name", ")", "{", "if", "(", "name", "===", "'change'", "||", "name", ".", "indexOf", "(", "'change:'", ")", "===", "0", ")", "{", "View", ".", "prototype", ".", "trigger", ".", "apply", "(", "this", ".", "view", ",", "arguments", ")", ";", "}", "if", "(", "name", ".", "indexOf", "(", "'change:hide:'", ")", "===", "0", ")", "{", "this", ".", "view", ".", "render", "(", ")", ";", "}", "NestedCell", ".", "prototype", ".", "trigger", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}" ]
Retrigger view state change events on the view as well. @method trigger @override
[ "Retrigger", "view", "state", "change", "events", "on", "the", "view", "as", "well", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2107-L2115
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(el, template, context, opts) { opts = opts || {}; if (_.isString(template)) { opts.newHTML = template; } templateRenderer.render(el, template, context, opts); }
javascript
function(el, template, context, opts) { opts = opts || {}; if (_.isString(template)) { opts.newHTML = template; } templateRenderer.render(el, template, context, opts); }
[ "function", "(", "el", ",", "template", ",", "context", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "_", ".", "isString", "(", "template", ")", ")", "{", "opts", ".", "newHTML", "=", "template", ";", "}", "templateRenderer", ".", "render", "(", "el", ",", "template", ",", "context", ",", "opts", ")", ";", "}" ]
Hotswap rendering system reroute method. @method templateRender See Torso.templateRenderer#render for params
[ "Hotswap", "rendering", "system", "reroute", "method", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2352-L2358
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { this.undelegateEvents(); // always undelegate events - backbone sometimes doesn't. Backbone.View.prototype.delegateEvents.call(this); this.__generateFeedbackBindings(); this.__generateFeedbackCellCallbacks(); _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent()) { view.delegateEvents(); } }); }
javascript
function() { this.undelegateEvents(); // always undelegate events - backbone sometimes doesn't. Backbone.View.prototype.delegateEvents.call(this); this.__generateFeedbackBindings(); this.__generateFeedbackCellCallbacks(); _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent()) { view.delegateEvents(); } }); }
[ "function", "(", ")", "{", "this", ".", "undelegateEvents", "(", ")", ";", "// always undelegate events - backbone sometimes doesn't.", "Backbone", ".", "View", ".", "prototype", ".", "delegateEvents", ".", "call", "(", "this", ")", ";", "this", ".", "__generateFeedbackBindings", "(", ")", ";", "this", ".", "__generateFeedbackCellCallbacks", "(", ")", ";", "_", ".", "each", "(", "this", ".", "getTrackedViews", "(", ")", ",", "function", "(", "view", ")", "{", "if", "(", "view", ".", "isAttachedToParent", "(", ")", ")", "{", "view", ".", "delegateEvents", "(", ")", ";", "}", "}", ")", ";", "}" ]
Overrides the base delegateEvents Binds DOM events with the view using events hash while also adding feedback event bindings @method delegateEvents
[ "Overrides", "the", "base", "delegateEvents", "Binds", "DOM", "events", "with", "the", "view", "using", "events", "hash", "while", "also", "adding", "feedback", "event", "bindings" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2365-L2375
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { Backbone.View.prototype.undelegateEvents.call(this); _.each(this.getTrackedViews(), function(view) { view.undelegateEvents(); }); }
javascript
function() { Backbone.View.prototype.undelegateEvents.call(this); _.each(this.getTrackedViews(), function(view) { view.undelegateEvents(); }); }
[ "function", "(", ")", "{", "Backbone", ".", "View", ".", "prototype", ".", "undelegateEvents", ".", "call", "(", "this", ")", ";", "_", ".", "each", "(", "this", ".", "getTrackedViews", "(", ")", ",", "function", "(", "view", ")", "{", "view", ".", "undelegateEvents", "(", ")", ";", "}", ")", ";", "}" ]
Overrides undelegateEvents Unbinds DOM events from the view. @method undelegateEvents
[ "Overrides", "undelegateEvents", "Unbinds", "DOM", "events", "from", "the", "view", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2382-L2387
train
vecnatechnologies/backbone-torso
torso-bundle.js
function($el, options) { options = options || {}; var view = this; if (!this.isAttachedToParent()) { this.__pendingAttachInfo = { $el: $el, options: options }; return this.render().done(function() { if (!view.__attachedCallbackInvoked && view.isAttached()) { view.__invokeAttached(); } view.__isAttachedToParent = true; }); } return $.Deferred().resolve().promise(); }
javascript
function($el, options) { options = options || {}; var view = this; if (!this.isAttachedToParent()) { this.__pendingAttachInfo = { $el: $el, options: options }; return this.render().done(function() { if (!view.__attachedCallbackInvoked && view.isAttached()) { view.__invokeAttached(); } view.__isAttachedToParent = true; }); } return $.Deferred().resolve().promise(); }
[ "function", "(", "$el", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "view", "=", "this", ";", "if", "(", "!", "this", ".", "isAttachedToParent", "(", ")", ")", "{", "this", ".", "__pendingAttachInfo", "=", "{", "$el", ":", "$el", ",", "options", ":", "options", "}", ";", "return", "this", ".", "render", "(", ")", ".", "done", "(", "function", "(", ")", "{", "if", "(", "!", "view", ".", "__attachedCallbackInvoked", "&&", "view", ".", "isAttached", "(", ")", ")", "{", "view", ".", "__invokeAttached", "(", ")", ";", "}", "view", ".", "__isAttachedToParent", "=", "true", ";", "}", ")", ";", "}", "return", "$", ".", "Deferred", "(", ")", ".", "resolve", "(", ")", ".", "promise", "(", ")", ";", "}" ]
If detached, will replace the element passed in with this view's element and activate the view. @param [$el] {jQuery element} the element to attach to. This element will be replaced with this view. If options.replaceMethod is provided, then this parameter is ignored. @param [options] {Object} optional options @param [options.replaceMethod] {Fucntion} if given, this view will invoke replaceMethod function in order to attach the view's DOM to the parent instead of calling $el.replaceWith @param [options.discardInjectionSite=false] {Booleon} if set to true, the injection site is not saved. @return {Promise} promise that when resolved, the attach process is complete. Normally this method is synchronous. Transition effects can make it asynchronous. @method attachTo
[ "If", "detached", "will", "replace", "the", "element", "passed", "in", "with", "this", "view", "s", "element", "and", "activate", "the", "view", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2401-L2417
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var wasAttached; if (this.isAttachedToParent()) { wasAttached = this.isAttached(); // Detach view from DOM this.trigger('before-dom-detach'); if (this.injectionSite) { this.$el.replaceWith(this.injectionSite); this.injectionSite = undefined; } else { this.$el.detach(); } if (wasAttached) { this.__invokeDetached(); } this.undelegateEvents(); this.__isAttachedToParent = false; } }
javascript
function() { var wasAttached; if (this.isAttachedToParent()) { wasAttached = this.isAttached(); // Detach view from DOM this.trigger('before-dom-detach'); if (this.injectionSite) { this.$el.replaceWith(this.injectionSite); this.injectionSite = undefined; } else { this.$el.detach(); } if (wasAttached) { this.__invokeDetached(); } this.undelegateEvents(); this.__isAttachedToParent = false; } }
[ "function", "(", ")", "{", "var", "wasAttached", ";", "if", "(", "this", ".", "isAttachedToParent", "(", ")", ")", "{", "wasAttached", "=", "this", ".", "isAttached", "(", ")", ";", "// Detach view from DOM", "this", ".", "trigger", "(", "'before-dom-detach'", ")", ";", "if", "(", "this", ".", "injectionSite", ")", "{", "this", ".", "$el", ".", "replaceWith", "(", "this", ".", "injectionSite", ")", ";", "this", ".", "injectionSite", "=", "undefined", ";", "}", "else", "{", "this", ".", "$el", ".", "detach", "(", ")", ";", "}", "if", "(", "wasAttached", ")", "{", "this", ".", "__invokeDetached", "(", ")", ";", "}", "this", ".", "undelegateEvents", "(", ")", ";", "this", ".", "__isAttachedToParent", "=", "false", ";", "}", "}" ]
If attached, will detach the view from the DOM. This method will only separate this view from the DOM it was attached to, but it WILL invoke the _detach callback on each tracked view recursively. @method detach
[ "If", "attached", "will", "detach", "the", "view", "from", "the", "DOM", ".", "This", "method", "will", "only", "separate", "this", "view", "from", "the", "DOM", "it", "was", "attached", "to", "but", "it", "WILL", "invoke", "the", "_detach", "callback", "on", "each", "tracked", "view", "recursively", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2511-L2529
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { this.trigger('before-dispose'); this.trigger('before-dispose-callback'); this._dispose(); // Detach DOM and deactivate the view this.detach(); this.deactivate(); // Clean up child views first this.__disposeChildViews(); // Remove view from DOM if (this.$el) { this.remove(); } // Unbind all local event bindings this.off(); this.stopListening(); if (this.viewState) { this.viewState.off(); this.viewState.stopListening(); } if (this.feedbackCell) { this.feedbackCell.off(); this.feedbackCell.stopListening(); } // Delete the dom references delete this.$el; delete this.el; this.__isDisposed = true; this.trigger('after-dispose'); }
javascript
function() { this.trigger('before-dispose'); this.trigger('before-dispose-callback'); this._dispose(); // Detach DOM and deactivate the view this.detach(); this.deactivate(); // Clean up child views first this.__disposeChildViews(); // Remove view from DOM if (this.$el) { this.remove(); } // Unbind all local event bindings this.off(); this.stopListening(); if (this.viewState) { this.viewState.off(); this.viewState.stopListening(); } if (this.feedbackCell) { this.feedbackCell.off(); this.feedbackCell.stopListening(); } // Delete the dom references delete this.$el; delete this.el; this.__isDisposed = true; this.trigger('after-dispose'); }
[ "function", "(", ")", "{", "this", ".", "trigger", "(", "'before-dispose'", ")", ";", "this", ".", "trigger", "(", "'before-dispose-callback'", ")", ";", "this", ".", "_dispose", "(", ")", ";", "// Detach DOM and deactivate the view", "this", ".", "detach", "(", ")", ";", "this", ".", "deactivate", "(", ")", ";", "// Clean up child views first", "this", ".", "__disposeChildViews", "(", ")", ";", "// Remove view from DOM", "if", "(", "this", ".", "$el", ")", "{", "this", ".", "remove", "(", ")", ";", "}", "// Unbind all local event bindings", "this", ".", "off", "(", ")", ";", "this", ".", "stopListening", "(", ")", ";", "if", "(", "this", ".", "viewState", ")", "{", "this", ".", "viewState", ".", "off", "(", ")", ";", "this", ".", "viewState", ".", "stopListening", "(", ")", ";", "}", "if", "(", "this", ".", "feedbackCell", ")", "{", "this", ".", "feedbackCell", ".", "off", "(", ")", ";", "this", ".", "feedbackCell", ".", "stopListening", "(", ")", ";", "}", "// Delete the dom references", "delete", "this", ".", "$el", ";", "delete", "this", ".", "el", ";", "this", ".", "__isDisposed", "=", "true", ";", "this", ".", "trigger", "(", "'after-dispose'", ")", ";", "}" ]
Removes all listeners, disposes children views, stops listening to events, removes DOM. After dispose is called, the view can be safely garbage collected. Called while recursively removing views from the hierarchy. @method dispose
[ "Removes", "all", "listeners", "disposes", "children", "views", "stops", "listening", "to", "events", "removes", "DOM", ".", "After", "dispose", "is", "called", "the", "view", "can", "be", "safely", "garbage", "collected", ".", "Called", "while", "recursively", "removing", "views", "from", "the", "hierarchy", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2609-L2643
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(view, options) { options = options || {}; this.unregisterTrackedView(view); if (options.child || !options.shared) { this.__childViews[view.cid] = view; } else { this.__sharedViews[view.cid] = view; } return view; }
javascript
function(view, options) { options = options || {}; this.unregisterTrackedView(view); if (options.child || !options.shared) { this.__childViews[view.cid] = view; } else { this.__sharedViews[view.cid] = view; } return view; }
[ "function", "(", "view", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "unregisterTrackedView", "(", "view", ")", ";", "if", "(", "options", ".", "child", "||", "!", "options", ".", "shared", ")", "{", "this", ".", "__childViews", "[", "view", ".", "cid", "]", "=", "view", ";", "}", "else", "{", "this", ".", "__sharedViews", "[", "view", ".", "cid", "]", "=", "view", ";", "}", "return", "view", ";", "}" ]
Binds the view as a tracked view - any recursive calls like activate, deactivate, or dispose will be done to the tracked view as well. Except dispose for shared views. This method defaults to register the view as a child view unless specified by options.shared. @param view {View} the tracked view @param [options={}] {Object} Optional options. @param [options.shared=false] {Boolean} If true, registers view as a shared view. These are views not owned by this parent. As compared to a child view which are disposed when the parent is disposed. If false, registers view as a child view which are disposed when the parent is disposed. @return {View} the tracked view @method registerTrackedView
[ "Binds", "the", "view", "as", "a", "tracked", "view", "-", "any", "recursive", "calls", "like", "activate", "deactivate", "or", "dispose", "will", "be", "done", "to", "the", "tracked", "view", "as", "well", ".", "Except", "dispose", "for", "shared", "views", ".", "This", "method", "defaults", "to", "register", "the", "view", "as", "a", "child", "view", "unless", "specified", "by", "options", ".", "shared", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2708-L2717
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(options) { var trackedViewsHash = this.getTrackedViews(options); _.each(trackedViewsHash, function(view) { this.unregisterTrackedView(view, options); }, this); }
javascript
function(options) { var trackedViewsHash = this.getTrackedViews(options); _.each(trackedViewsHash, function(view) { this.unregisterTrackedView(view, options); }, this); }
[ "function", "(", "options", ")", "{", "var", "trackedViewsHash", "=", "this", ".", "getTrackedViews", "(", "options", ")", ";", "_", ".", "each", "(", "trackedViewsHash", ",", "function", "(", "view", ")", "{", "this", ".", "unregisterTrackedView", "(", "view", ",", "options", ")", ";", "}", ",", "this", ")", ";", "}" ]
Unbinds all tracked view - no recursive calls will be made to this shared view You can limit the types of views that will be unregistered by using the options parameter. @param view {View} the shared view @param [options={}] {Object} Optional options. @param [options.shared=false] {Boolean} If true, unregister only the shared views. These are views not owned by this parent. As compared to a child view which are disposed when the parent is disposed. @param [options.child=false] {Boolean} If true, unregister only child views. These are views that are owned by the parent and dispose of them if the parent is disposed. @return {View} the tracked view @method unregisterTrackedView
[ "Unbinds", "all", "tracked", "view", "-", "no", "recursive", "calls", "will", "be", "made", "to", "this", "shared", "view", "You", "can", "limit", "the", "types", "of", "views", "that", "will", "be", "unregistered", "by", "using", "the", "options", "parameter", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2742-L2747
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(to, evt, indexMap) { var result, feedbackToInvoke = _.find(this.feedback, function(feedback) { var toToCheck = feedback.to; if (_.isArray(toToCheck)) { return _.contains(toToCheck, to); } else { return to === toToCheck; } }), feedbackCellField = to; if (feedbackToInvoke) { if (indexMap) { feedbackCellField = this.__substituteIndicesUsingMap(to, indexMap); } result = feedbackToInvoke.then.call(this, evt, indexMap); this.__processFeedbackThenResult(result, feedbackCellField); } }
javascript
function(to, evt, indexMap) { var result, feedbackToInvoke = _.find(this.feedback, function(feedback) { var toToCheck = feedback.to; if (_.isArray(toToCheck)) { return _.contains(toToCheck, to); } else { return to === toToCheck; } }), feedbackCellField = to; if (feedbackToInvoke) { if (indexMap) { feedbackCellField = this.__substituteIndicesUsingMap(to, indexMap); } result = feedbackToInvoke.then.call(this, evt, indexMap); this.__processFeedbackThenResult(result, feedbackCellField); } }
[ "function", "(", "to", ",", "evt", ",", "indexMap", ")", "{", "var", "result", ",", "feedbackToInvoke", "=", "_", ".", "find", "(", "this", ".", "feedback", ",", "function", "(", "feedback", ")", "{", "var", "toToCheck", "=", "feedback", ".", "to", ";", "if", "(", "_", ".", "isArray", "(", "toToCheck", ")", ")", "{", "return", "_", ".", "contains", "(", "toToCheck", ",", "to", ")", ";", "}", "else", "{", "return", "to", "===", "toToCheck", ";", "}", "}", ")", ",", "feedbackCellField", "=", "to", ";", "if", "(", "feedbackToInvoke", ")", "{", "if", "(", "indexMap", ")", "{", "feedbackCellField", "=", "this", ".", "__substituteIndicesUsingMap", "(", "to", ",", "indexMap", ")", ";", "}", "result", "=", "feedbackToInvoke", ".", "then", ".", "call", "(", "this", ",", "evt", ",", "indexMap", ")", ";", "this", ".", "__processFeedbackThenResult", "(", "result", ",", "feedbackCellField", ")", ";", "}", "}" ]
Invokes a feedback entry's "then" method @param to {String} the "to" field corresponding to the feedback entry to be invoked. @param [evt] {Event} the event to be passed to the "then" method @param [indexMap] {Object} a map from index variable name to index value. Needed for "to" fields with array notation. @method invokeFeedback
[ "Invokes", "a", "feedback", "entry", "s", "then", "method" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2788-L2806
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(viewOptions) { var view = this; if (!_.isEmpty(this.behaviors)) { view.__behaviorInstances = {}; _.each(this.behaviors, function(behaviorDefinition, alias) { if (!_.has(behaviorDefinition, 'behavior')) { behaviorDefinition = {behavior: behaviorDefinition}; } var BehaviorClass = behaviorDefinition.behavior; if (!(BehaviorClass && _.isFunction(BehaviorClass))) { throw new Error('Incorrect behavior definition. Expected key "behavior" to be a class but instead got ' + String(BehaviorClass)); } var behaviorOptions = _.pick(behaviorDefinition, function(value, key) { return key !== 'behavior'; }); behaviorOptions.view = view; behaviorOptions.alias = alias; var behaviorAttributes = behaviorDefinition.attributes || {}; var behaviorInstance = view.__behaviorInstances[alias] = new BehaviorClass(behaviorAttributes, behaviorOptions, viewOptions); // Add the behavior's mixin fields to the view's public API if (behaviorInstance.mixin) { var mixin = _.result(behaviorInstance, 'mixin'); _.each(mixin, function(field, fieldName) { // Default to a view's field over a behavior mixin if (_.isUndefined(view[fieldName])) { if (_.isFunction(field)) { // Behavior mixin functions will be behavior-scoped - the context will be the behavior. view[fieldName] = _.bind(field, behaviorInstance); } else { view[fieldName] = field; } } }); } }); } }
javascript
function(viewOptions) { var view = this; if (!_.isEmpty(this.behaviors)) { view.__behaviorInstances = {}; _.each(this.behaviors, function(behaviorDefinition, alias) { if (!_.has(behaviorDefinition, 'behavior')) { behaviorDefinition = {behavior: behaviorDefinition}; } var BehaviorClass = behaviorDefinition.behavior; if (!(BehaviorClass && _.isFunction(BehaviorClass))) { throw new Error('Incorrect behavior definition. Expected key "behavior" to be a class but instead got ' + String(BehaviorClass)); } var behaviorOptions = _.pick(behaviorDefinition, function(value, key) { return key !== 'behavior'; }); behaviorOptions.view = view; behaviorOptions.alias = alias; var behaviorAttributes = behaviorDefinition.attributes || {}; var behaviorInstance = view.__behaviorInstances[alias] = new BehaviorClass(behaviorAttributes, behaviorOptions, viewOptions); // Add the behavior's mixin fields to the view's public API if (behaviorInstance.mixin) { var mixin = _.result(behaviorInstance, 'mixin'); _.each(mixin, function(field, fieldName) { // Default to a view's field over a behavior mixin if (_.isUndefined(view[fieldName])) { if (_.isFunction(field)) { // Behavior mixin functions will be behavior-scoped - the context will be the behavior. view[fieldName] = _.bind(field, behaviorInstance); } else { view[fieldName] = field; } } }); } }); } }
[ "function", "(", "viewOptions", ")", "{", "var", "view", "=", "this", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "this", ".", "behaviors", ")", ")", "{", "view", ".", "__behaviorInstances", "=", "{", "}", ";", "_", ".", "each", "(", "this", ".", "behaviors", ",", "function", "(", "behaviorDefinition", ",", "alias", ")", "{", "if", "(", "!", "_", ".", "has", "(", "behaviorDefinition", ",", "'behavior'", ")", ")", "{", "behaviorDefinition", "=", "{", "behavior", ":", "behaviorDefinition", "}", ";", "}", "var", "BehaviorClass", "=", "behaviorDefinition", ".", "behavior", ";", "if", "(", "!", "(", "BehaviorClass", "&&", "_", ".", "isFunction", "(", "BehaviorClass", ")", ")", ")", "{", "throw", "new", "Error", "(", "'Incorrect behavior definition. Expected key \"behavior\" to be a class but instead got '", "+", "String", "(", "BehaviorClass", ")", ")", ";", "}", "var", "behaviorOptions", "=", "_", ".", "pick", "(", "behaviorDefinition", ",", "function", "(", "value", ",", "key", ")", "{", "return", "key", "!==", "'behavior'", ";", "}", ")", ";", "behaviorOptions", ".", "view", "=", "view", ";", "behaviorOptions", ".", "alias", "=", "alias", ";", "var", "behaviorAttributes", "=", "behaviorDefinition", ".", "attributes", "||", "{", "}", ";", "var", "behaviorInstance", "=", "view", ".", "__behaviorInstances", "[", "alias", "]", "=", "new", "BehaviorClass", "(", "behaviorAttributes", ",", "behaviorOptions", ",", "viewOptions", ")", ";", "// Add the behavior's mixin fields to the view's public API", "if", "(", "behaviorInstance", ".", "mixin", ")", "{", "var", "mixin", "=", "_", ".", "result", "(", "behaviorInstance", ",", "'mixin'", ")", ";", "_", ".", "each", "(", "mixin", ",", "function", "(", "field", ",", "fieldName", ")", "{", "// Default to a view's field over a behavior mixin", "if", "(", "_", ".", "isUndefined", "(", "view", "[", "fieldName", "]", ")", ")", "{", "if", "(", "_", ".", "isFunction", "(", "field", ")", ")", "{", "// Behavior mixin functions will be behavior-scoped - the context will be the behavior.", "view", "[", "fieldName", "]", "=", "_", ".", "bind", "(", "field", ",", "behaviorInstance", ")", ";", "}", "else", "{", "view", "[", "fieldName", "]", "=", "field", ";", "}", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}" ]
Initializes the behaviors @method __initializeBehaviors
[ "Initializes", "the", "behaviors" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L2966-L3004
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(injectionSiteName, previousView, newView, options) { var newInjectionSite, currentPromise, previousDeferred = $.Deferred(); this.attachView(injectionSiteName, previousView, options); options.cachedInjectionSite = previousView.injectionSite; newInjectionSite = options.newInjectionSite = $('<span inject="' + injectionSiteName + '">'); if (options.addBefore) { previousView.$el.before(newInjectionSite); } else { previousView.$el.after(newInjectionSite); } // clear the injections site so it isn't replaced back into the dom. previousView.injectionSite = undefined; // transition previous view out previousView.transitionOut(previousDeferred.resolve, options); // transition new current view in currentPromise = this.__transitionInView(newInjectionSite, newView, options); // return a combined promise return $.when(previousDeferred.promise(), currentPromise); }
javascript
function(injectionSiteName, previousView, newView, options) { var newInjectionSite, currentPromise, previousDeferred = $.Deferred(); this.attachView(injectionSiteName, previousView, options); options.cachedInjectionSite = previousView.injectionSite; newInjectionSite = options.newInjectionSite = $('<span inject="' + injectionSiteName + '">'); if (options.addBefore) { previousView.$el.before(newInjectionSite); } else { previousView.$el.after(newInjectionSite); } // clear the injections site so it isn't replaced back into the dom. previousView.injectionSite = undefined; // transition previous view out previousView.transitionOut(previousDeferred.resolve, options); // transition new current view in currentPromise = this.__transitionInView(newInjectionSite, newView, options); // return a combined promise return $.when(previousDeferred.promise(), currentPromise); }
[ "function", "(", "injectionSiteName", ",", "previousView", ",", "newView", ",", "options", ")", "{", "var", "newInjectionSite", ",", "currentPromise", ",", "previousDeferred", "=", "$", ".", "Deferred", "(", ")", ";", "this", ".", "attachView", "(", "injectionSiteName", ",", "previousView", ",", "options", ")", ";", "options", ".", "cachedInjectionSite", "=", "previousView", ".", "injectionSite", ";", "newInjectionSite", "=", "options", ".", "newInjectionSite", "=", "$", "(", "'<span inject=\"'", "+", "injectionSiteName", "+", "'\">'", ")", ";", "if", "(", "options", ".", "addBefore", ")", "{", "previousView", ".", "$el", ".", "before", "(", "newInjectionSite", ")", ";", "}", "else", "{", "previousView", ".", "$el", ".", "after", "(", "newInjectionSite", ")", ";", "}", "// clear the injections site so it isn't replaced back into the dom.", "previousView", ".", "injectionSite", "=", "undefined", ";", "// transition previous view out", "previousView", ".", "transitionOut", "(", "previousDeferred", ".", "resolve", ",", "options", ")", ";", "// transition new current view in", "currentPromise", "=", "this", ".", "__transitionInView", "(", "newInjectionSite", ",", "newView", ",", "options", ")", ";", "// return a combined promise", "return", "$", ".", "when", "(", "previousDeferred", ".", "promise", "(", ")", ",", "currentPromise", ")", ";", "}" ]
Will transition out previousView at the same time as transitioning in newView. @method __performTwoWayTransition @param injectionSiteName {String} The name of the injection site in the template. This is the value corresponding to the attribute "inject". @param previousView {View} the view that should be transitioned out. @param newView {View} The view that should be transitioned into the injection site @param [options] {Object} optional options object. This options object will be passed on to the transitionIn and transitionOut methods as well. @param [options.addBefore=false] {Boolean} if true, the new view's element will be added before the previous view's element. Defaults to after. @return {Promise} resolved when all transitions are complete. No payload is provided upon resolution. @private
[ "Will", "transition", "out", "previousView", "at", "the", "same", "time", "as", "transitioning", "in", "newView", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3121-L3143
train
vecnatechnologies/backbone-torso
torso-bundle.js
function($el, newView, options) { var currentDeferred = $.Deferred(), parentView = this; options = _.extend({}, options); _.defaults(options, { parentView: this, newView: newView }); newView.transitionIn(function() { parentView.attachView($el, newView, options); }, currentDeferred.resolve, options); return currentDeferred.promise(); }
javascript
function($el, newView, options) { var currentDeferred = $.Deferred(), parentView = this; options = _.extend({}, options); _.defaults(options, { parentView: this, newView: newView }); newView.transitionIn(function() { parentView.attachView($el, newView, options); }, currentDeferred.resolve, options); return currentDeferred.promise(); }
[ "function", "(", "$el", ",", "newView", ",", "options", ")", "{", "var", "currentDeferred", "=", "$", ".", "Deferred", "(", ")", ",", "parentView", "=", "this", ";", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "options", ")", ";", "_", ".", "defaults", "(", "options", ",", "{", "parentView", ":", "this", ",", "newView", ":", "newView", "}", ")", ";", "newView", ".", "transitionIn", "(", "function", "(", ")", "{", "parentView", ".", "attachView", "(", "$el", ",", "newView", ",", "options", ")", ";", "}", ",", "currentDeferred", ".", "resolve", ",", "options", ")", ";", "return", "currentDeferred", ".", "promise", "(", ")", ";", "}" ]
Simliar to this.attachView except it utilizes the new view's transitionIn method instead of just attaching the view. This method is invoked on the parent view to attach a tracked view where the transitionIn method defines how a tracked view is brought onto the page. @param $el {jQuery element} the element to attach to. @param newView {View} the view to be transitioned in. @param [options] {Object} optional options object @param [options.noActivate=false] {Boolean} if set to true, the view will not be activated upon attaching. @param [options.shared=false] {Boolean} if set to true, the view will be treated as a shared view and not disposed during parent view disposing. @return {Promise} resolved when transition is complete. No payload is provided upon resolution. @method transitionInView @private
[ "Simliar", "to", "this", ".", "attachView", "except", "it", "utilizes", "the", "new", "view", "s", "transitionIn", "method", "instead", "of", "just", "attaching", "the", "view", ".", "This", "method", "is", "invoked", "on", "the", "parent", "view", "to", "attach", "a", "tracked", "view", "where", "the", "transitionIn", "method", "defines", "how", "a", "tracked", "view", "is", "brought", "onto", "the", "page", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3157-L3169
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var parentView = this; this.__injectionSiteMap = {}; this.__lastTrackedViews = {}; _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent() && view.injectionSite) { parentView.__injectionSiteMap[view.injectionSite.attr('inject')] = view; } parentView.__lastTrackedViews[view.cid] = view; }); }
javascript
function() { var parentView = this; this.__injectionSiteMap = {}; this.__lastTrackedViews = {}; _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent() && view.injectionSite) { parentView.__injectionSiteMap[view.injectionSite.attr('inject')] = view; } parentView.__lastTrackedViews[view.cid] = view; }); }
[ "function", "(", ")", "{", "var", "parentView", "=", "this", ";", "this", ".", "__injectionSiteMap", "=", "{", "}", ";", "this", ".", "__lastTrackedViews", "=", "{", "}", ";", "_", ".", "each", "(", "this", ".", "getTrackedViews", "(", ")", ",", "function", "(", "view", ")", "{", "if", "(", "view", ".", "isAttachedToParent", "(", ")", "&&", "view", ".", "injectionSite", ")", "{", "parentView", ".", "__injectionSiteMap", "[", "view", ".", "injectionSite", ".", "attr", "(", "'inject'", ")", "]", "=", "view", ";", "}", "parentView", ".", "__lastTrackedViews", "[", "view", ".", "cid", "]", "=", "view", ";", "}", ")", ";", "}" ]
Used internally by Torso.View to keep a cache of tracked views and their current injection sites before detaching during render logic. @private @method __updateInjectionSiteMap
[ "Used", "internally", "by", "Torso", ".", "View", "to", "keep", "a", "cache", "of", "tracked", "views", "and", "their", "current", "injection", "sites", "before", "detaching", "during", "render", "logic", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3203-L3213
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { // Need to check if each view is attached because there is no guarentee that if parent is attached, child is attached. if (!this.__attachedCallbackInvoked) { this.trigger('before-attached-callback'); this._attached(); this.__attachedCallbackInvoked = true; _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent()) { view.__invokeAttached(); } }); } }
javascript
function() { // Need to check if each view is attached because there is no guarentee that if parent is attached, child is attached. if (!this.__attachedCallbackInvoked) { this.trigger('before-attached-callback'); this._attached(); this.__attachedCallbackInvoked = true; _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent()) { view.__invokeAttached(); } }); } }
[ "function", "(", ")", "{", "// Need to check if each view is attached because there is no guarentee that if parent is attached, child is attached.", "if", "(", "!", "this", ".", "__attachedCallbackInvoked", ")", "{", "this", ".", "trigger", "(", "'before-attached-callback'", ")", ";", "this", ".", "_attached", "(", ")", ";", "this", ".", "__attachedCallbackInvoked", "=", "true", ";", "_", ".", "each", "(", "this", ".", "getTrackedViews", "(", ")", ",", "function", "(", "view", ")", "{", "if", "(", "view", ".", "isAttachedToParent", "(", ")", ")", "{", "view", ".", "__invokeAttached", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Call this method when a view is attached to the DOM. It is recursive to child views, but checks whether each child view is attached. @method __invokeAttached @private
[ "Call", "this", "method", "when", "a", "view", "is", "attached", "to", "the", "DOM", ".", "It", "is", "recursive", "to", "child", "views", "but", "checks", "whether", "each", "child", "view", "is", "attached", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3237-L3249
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { if (this.__attachedCallbackInvoked) { this.trigger('before-detached-callback'); this._detached(); this.__attachedCallbackInvoked = false; } _.each(this.getTrackedViews(), function(view) { // If the tracked view is currently attached to the parent, then invoke detatched on it. if (view.isAttachedToParent()) { view.__invokeDetached(); } }); }
javascript
function() { if (this.__attachedCallbackInvoked) { this.trigger('before-detached-callback'); this._detached(); this.__attachedCallbackInvoked = false; } _.each(this.getTrackedViews(), function(view) { // If the tracked view is currently attached to the parent, then invoke detatched on it. if (view.isAttachedToParent()) { view.__invokeDetached(); } }); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "__attachedCallbackInvoked", ")", "{", "this", ".", "trigger", "(", "'before-detached-callback'", ")", ";", "this", ".", "_detached", "(", ")", ";", "this", ".", "__attachedCallbackInvoked", "=", "false", ";", "}", "_", ".", "each", "(", "this", ".", "getTrackedViews", "(", ")", ",", "function", "(", "view", ")", "{", "// If the tracked view is currently attached to the parent, then invoke detatched on it.", "if", "(", "view", ".", "isAttachedToParent", "(", ")", ")", "{", "view", ".", "__invokeDetached", "(", ")", ";", "}", "}", ")", ";", "}" ]
Call this method when a view is detached from the DOM. It is recursive to child views. @method __invokeDetached
[ "Call", "this", "method", "when", "a", "view", "is", "detached", "from", "the", "DOM", ".", "It", "is", "recursive", "to", "child", "views", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3255-L3267
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(result, feedbackCellField) { var newState = $.extend({}, result); this.feedbackCell.set(feedbackCellField, newState, {silent: true}); this.feedbackCell.trigger('change:' + feedbackCellField); }
javascript
function(result, feedbackCellField) { var newState = $.extend({}, result); this.feedbackCell.set(feedbackCellField, newState, {silent: true}); this.feedbackCell.trigger('change:' + feedbackCellField); }
[ "function", "(", "result", ",", "feedbackCellField", ")", "{", "var", "newState", "=", "$", ".", "extend", "(", "{", "}", ",", "result", ")", ";", "this", ".", "feedbackCell", ".", "set", "(", "feedbackCellField", ",", "newState", ",", "{", "silent", ":", "true", "}", ")", ";", "this", ".", "feedbackCell", ".", "trigger", "(", "'change:'", "+", "feedbackCellField", ")", ";", "}" ]
Processes the result of the then method. Adds to the feedback cell. @param result {Object} the result of the then method @param feedbackCellField {Object} the name of the feedbackCellField, typically the "to" value. @private @method __processFeedbackThenResult
[ "Processes", "the", "result", "of", "the", "then", "method", ".", "Adds", "to", "the", "feedback", "cell", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3323-L3327
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(bindInfo, eventKey) { return function() { var result, args = [{ args: arguments, type: eventKey }]; args.push(bindInfo.indices); result = bindInfo.fn.apply(this, args); this.__processFeedbackThenResult(result, bindInfo.feedbackCellField); }; }
javascript
function(bindInfo, eventKey) { return function() { var result, args = [{ args: arguments, type: eventKey }]; args.push(bindInfo.indices); result = bindInfo.fn.apply(this, args); this.__processFeedbackThenResult(result, bindInfo.feedbackCellField); }; }
[ "function", "(", "bindInfo", ",", "eventKey", ")", "{", "return", "function", "(", ")", "{", "var", "result", ",", "args", "=", "[", "{", "args", ":", "arguments", ",", "type", ":", "eventKey", "}", "]", ";", "args", ".", "push", "(", "bindInfo", ".", "indices", ")", ";", "result", "=", "bindInfo", ".", "fn", ".", "apply", "(", "this", ",", "args", ")", ";", "this", ".", "__processFeedbackThenResult", "(", "result", ",", "bindInfo", ".", "feedbackCellField", ")", ";", "}", ";", "}" ]
Returns a properly wrapped "then" using a configuration object "bindInfo" and an "eventKey" that will be passed as the type @param bindInfo {Object} @param bindInfo.feedbackCellField the property name of the feedback cell to store the "then" instructions @param bindInfo.fn the original "then" function @param [bindInfo.indices] the index map @return {Function} the properly wrapped "then" function @private @method __generateThenCallback
[ "Returns", "a", "properly", "wrapped", "then", "using", "a", "configuration", "object", "bindInfo", "and", "an", "eventKey", "that", "will", "be", "passed", "as", "the", "type" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3448-L3459
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(whenMap, indexMap) { var self = this, events = []; _.each(whenMap, function(whenEvents, whenField) { var substitutedWhenField, qualifiedFields = [whenField], useAtNotation = (whenField.charAt(0) === '@'); if (whenField !== 'on' || whenField !== 'listenTo') { if (useAtNotation) { whenField = whenField.substring(1); // substitute indices in to "when" placeholders // [] -> to all, [0] -> to specific, [x] -> [x's value] substitutedWhenField = self.__substituteIndicesUsingMap(whenField, indexMap); qualifiedFields = _.flatten(self.__generateSubAttributes(substitutedWhenField, self.model)); } // For each qualified field _.each(qualifiedFields, function(qualifiedField) { _.each(whenEvents, function(eventType) { var backboneEvent = eventType + ' ' + qualifiedField; if (useAtNotation) { backboneEvent = eventType + ' [data-model="' + qualifiedField + '"]'; } events.push(backboneEvent); }); }); } }); return events; }
javascript
function(whenMap, indexMap) { var self = this, events = []; _.each(whenMap, function(whenEvents, whenField) { var substitutedWhenField, qualifiedFields = [whenField], useAtNotation = (whenField.charAt(0) === '@'); if (whenField !== 'on' || whenField !== 'listenTo') { if (useAtNotation) { whenField = whenField.substring(1); // substitute indices in to "when" placeholders // [] -> to all, [0] -> to specific, [x] -> [x's value] substitutedWhenField = self.__substituteIndicesUsingMap(whenField, indexMap); qualifiedFields = _.flatten(self.__generateSubAttributes(substitutedWhenField, self.model)); } // For each qualified field _.each(qualifiedFields, function(qualifiedField) { _.each(whenEvents, function(eventType) { var backboneEvent = eventType + ' ' + qualifiedField; if (useAtNotation) { backboneEvent = eventType + ' [data-model="' + qualifiedField + '"]'; } events.push(backboneEvent); }); }); } }); return events; }
[ "function", "(", "whenMap", ",", "indexMap", ")", "{", "var", "self", "=", "this", ",", "events", "=", "[", "]", ";", "_", ".", "each", "(", "whenMap", ",", "function", "(", "whenEvents", ",", "whenField", ")", "{", "var", "substitutedWhenField", ",", "qualifiedFields", "=", "[", "whenField", "]", ",", "useAtNotation", "=", "(", "whenField", ".", "charAt", "(", "0", ")", "===", "'@'", ")", ";", "if", "(", "whenField", "!==", "'on'", "||", "whenField", "!==", "'listenTo'", ")", "{", "if", "(", "useAtNotation", ")", "{", "whenField", "=", "whenField", ".", "substring", "(", "1", ")", ";", "// substitute indices in to \"when\" placeholders", "// [] -> to all, [0] -> to specific, [x] -> [x's value]", "substitutedWhenField", "=", "self", ".", "__substituteIndicesUsingMap", "(", "whenField", ",", "indexMap", ")", ";", "qualifiedFields", "=", "_", ".", "flatten", "(", "self", ".", "__generateSubAttributes", "(", "substitutedWhenField", ",", "self", ".", "model", ")", ")", ";", "}", "// For each qualified field", "_", ".", "each", "(", "qualifiedFields", ",", "function", "(", "qualifiedField", ")", "{", "_", ".", "each", "(", "whenEvents", ",", "function", "(", "eventType", ")", "{", "var", "backboneEvent", "=", "eventType", "+", "' '", "+", "qualifiedField", ";", "if", "(", "useAtNotation", ")", "{", "backboneEvent", "=", "eventType", "+", "' [data-model=\"'", "+", "qualifiedField", "+", "'\"]'", ";", "}", "events", ".", "push", "(", "backboneEvent", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "events", ";", "}" ]
Generates the events needed to listen to the feedback's when methods. A when event is only created if the appropriate element exist on the page @param whenMap the collection of "when"'s for a given feedback @param indexMap map from variable names to values when substituting array notation @return the events that were generated @private @method __generateWhenEvents
[ "Generates", "the", "events", "needed", "to", "listen", "to", "the", "feedback", "s", "when", "methods", ".", "A", "when", "event", "is", "only", "created", "if", "the", "appropriate", "element", "exist", "on", "the", "page" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3493-L3522
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model, attr) { var attrValidationSet = model.validation ? _.result(model, 'validation')[attr] || {} : {}; // If the validator is a function or a string, wrap it in a function validator if (_.isFunction(attrValidationSet) || _.isString(attrValidationSet)) { attrValidationSet = { fn: attrValidationSet }; } // Stick the validator object into an array if(!_.isArray(attrValidationSet)) { attrValidationSet = [attrValidationSet]; } // Reduces the array of validators into a new array with objects // with a validation method to call, the value to validate against // and the specified error message, if any return _.reduce(attrValidationSet, function(memo, attrValidation) { _.each(_.without(_.keys(attrValidation), 'msg', 'msgKey'), function(validator) { memo.push({ fn: defaultValidators[validator], val: attrValidation[validator], msg: attrValidation.msg, msgKey: attrValidation.msgKey }); }); return memo; }, []); }
javascript
function(model, attr) { var attrValidationSet = model.validation ? _.result(model, 'validation')[attr] || {} : {}; // If the validator is a function or a string, wrap it in a function validator if (_.isFunction(attrValidationSet) || _.isString(attrValidationSet)) { attrValidationSet = { fn: attrValidationSet }; } // Stick the validator object into an array if(!_.isArray(attrValidationSet)) { attrValidationSet = [attrValidationSet]; } // Reduces the array of validators into a new array with objects // with a validation method to call, the value to validate against // and the specified error message, if any return _.reduce(attrValidationSet, function(memo, attrValidation) { _.each(_.without(_.keys(attrValidation), 'msg', 'msgKey'), function(validator) { memo.push({ fn: defaultValidators[validator], val: attrValidation[validator], msg: attrValidation.msg, msgKey: attrValidation.msgKey }); }); return memo; }, []); }
[ "function", "(", "model", ",", "attr", ")", "{", "var", "attrValidationSet", "=", "model", ".", "validation", "?", "_", ".", "result", "(", "model", ",", "'validation'", ")", "[", "attr", "]", "||", "{", "}", ":", "{", "}", ";", "// If the validator is a function or a string, wrap it in a function validator", "if", "(", "_", ".", "isFunction", "(", "attrValidationSet", ")", "||", "_", ".", "isString", "(", "attrValidationSet", ")", ")", "{", "attrValidationSet", "=", "{", "fn", ":", "attrValidationSet", "}", ";", "}", "// Stick the validator object into an array", "if", "(", "!", "_", ".", "isArray", "(", "attrValidationSet", ")", ")", "{", "attrValidationSet", "=", "[", "attrValidationSet", "]", ";", "}", "// Reduces the array of validators into a new array with objects", "// with a validation method to call, the value to validate against", "// and the specified error message, if any", "return", "_", ".", "reduce", "(", "attrValidationSet", ",", "function", "(", "memo", ",", "attrValidation", ")", "{", "_", ".", "each", "(", "_", ".", "without", "(", "_", ".", "keys", "(", "attrValidation", ")", ",", "'msg'", ",", "'msgKey'", ")", ",", "function", "(", "validator", ")", "{", "memo", ".", "push", "(", "{", "fn", ":", "defaultValidators", "[", "validator", "]", ",", "val", ":", "attrValidation", "[", "validator", "]", ",", "msg", ":", "attrValidation", ".", "msg", ",", "msgKey", ":", "attrValidation", ".", "msgKey", "}", ")", ";", "}", ")", ";", "return", "memo", ";", "}", ",", "[", "]", ")", ";", "}" ]
Looks on the model for validations for a specified attribute. Returns an array of any validators defined, or an empty array if none is defined.
[ "Looks", "on", "the", "model", "for", "validations", "for", "a", "specified", "attribute", ".", "Returns", "an", "array", "of", "any", "validators", "defined", "or", "an", "empty", "array", "if", "none", "is", "defined", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3762-L3791
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model, attrs, validatedAttrs) { var error, invalidAttrs = {}, isValid = true, computed = _.clone(attrs); _.each(validatedAttrs, function(val, attr) { error = validateAttrWithOpenArray(model, attr, val, computed); if (error) { invalidAttrs[attr] = error; isValid = false; } }); return { invalidAttrs: invalidAttrs, isValid: isValid }; }
javascript
function(model, attrs, validatedAttrs) { var error, invalidAttrs = {}, isValid = true, computed = _.clone(attrs); _.each(validatedAttrs, function(val, attr) { error = validateAttrWithOpenArray(model, attr, val, computed); if (error) { invalidAttrs[attr] = error; isValid = false; } }); return { invalidAttrs: invalidAttrs, isValid: isValid }; }
[ "function", "(", "model", ",", "attrs", ",", "validatedAttrs", ")", "{", "var", "error", ",", "invalidAttrs", "=", "{", "}", ",", "isValid", "=", "true", ",", "computed", "=", "_", ".", "clone", "(", "attrs", ")", ";", "_", ".", "each", "(", "validatedAttrs", ",", "function", "(", "val", ",", "attr", ")", "{", "error", "=", "validateAttrWithOpenArray", "(", "model", ",", "attr", ",", "val", ",", "computed", ")", ";", "if", "(", "error", ")", "{", "invalidAttrs", "[", "attr", "]", "=", "error", ";", "isValid", "=", "false", ";", "}", "}", ")", ";", "return", "{", "invalidAttrs", ":", "invalidAttrs", ",", "isValid", ":", "isValid", "}", ";", "}" ]
Loops through the model's attributes and validates the specified attrs. Returns and object containing names of invalid attributes as well as error messages.
[ "Loops", "through", "the", "model", "s", "attributes", "and", "validates", "the", "specified", "attrs", ".", "Returns", "and", "object", "containing", "names", "of", "invalid", "attributes", "as", "well", "as", "error", "messages", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3933-L3951
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model, value, attr) { var indices, validators, validations = model.validation ? _.result(model, 'validation') || {} : {}; // If the validations hash contains an entry for the attr if (_.contains(_.keys(validations), attr)) { return validateAttrWithOpenArray(model, attr, value, _.extend({}, model.attributes)); } else { indices = extractIndices(attr); attr = stripIndices(attr); validators = getValidators(model, attr); return invokeValidator(validators, model, value, attr, _.extend({}, model.attributes), indices); } }
javascript
function(model, value, attr) { var indices, validators, validations = model.validation ? _.result(model, 'validation') || {} : {}; // If the validations hash contains an entry for the attr if (_.contains(_.keys(validations), attr)) { return validateAttrWithOpenArray(model, attr, value, _.extend({}, model.attributes)); } else { indices = extractIndices(attr); attr = stripIndices(attr); validators = getValidators(model, attr); return invokeValidator(validators, model, value, attr, _.extend({}, model.attributes), indices); } }
[ "function", "(", "model", ",", "value", ",", "attr", ")", "{", "var", "indices", ",", "validators", ",", "validations", "=", "model", ".", "validation", "?", "_", ".", "result", "(", "model", ",", "'validation'", ")", "||", "{", "}", ":", "{", "}", ";", "// If the validations hash contains an entry for the attr", "if", "(", "_", ".", "contains", "(", "_", ".", "keys", "(", "validations", ")", ",", "attr", ")", ")", "{", "return", "validateAttrWithOpenArray", "(", "model", ",", "attr", ",", "value", ",", "_", ".", "extend", "(", "{", "}", ",", "model", ".", "attributes", ")", ")", ";", "}", "else", "{", "indices", "=", "extractIndices", "(", "attr", ")", ";", "attr", "=", "stripIndices", "(", "attr", ")", ";", "validators", "=", "getValidators", "(", "model", ",", "attr", ")", ";", "return", "invokeValidator", "(", "validators", ",", "model", ",", "value", ",", "attr", ",", "_", ".", "extend", "(", "{", "}", ",", "model", ".", "attributes", ")", ",", "indices", ")", ";", "}", "}" ]
Validates attribute without open array notation.
[ "Validates", "attribute", "without", "open", "array", "notation", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3954-L3966
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(attr, value) { var self = this, result = {}, error; if (_.isArray(attr)) { _.each(attr, function(attr) { error = self.preValidate(attr); if (error) { result[attr] = error; } }); return _.isEmpty(result) ? undefined : result; } else if (_.isObject(attr)) { _.each(attr, function(value, key) { error = self.preValidate(key, value); if (error) { result[key] = error; } }); return _.isEmpty(result) ? undefined : result; } else { if (_.isUndefined(value) && isNestedModel(this)) { value = this.get(attr); } return validateAttr(this, value, attr); } }
javascript
function(attr, value) { var self = this, result = {}, error; if (_.isArray(attr)) { _.each(attr, function(attr) { error = self.preValidate(attr); if (error) { result[attr] = error; } }); return _.isEmpty(result) ? undefined : result; } else if (_.isObject(attr)) { _.each(attr, function(value, key) { error = self.preValidate(key, value); if (error) { result[key] = error; } }); return _.isEmpty(result) ? undefined : result; } else { if (_.isUndefined(value) && isNestedModel(this)) { value = this.get(attr); } return validateAttr(this, value, attr); } }
[ "function", "(", "attr", ",", "value", ")", "{", "var", "self", "=", "this", ",", "result", "=", "{", "}", ",", "error", ";", "if", "(", "_", ".", "isArray", "(", "attr", ")", ")", "{", "_", ".", "each", "(", "attr", ",", "function", "(", "attr", ")", "{", "error", "=", "self", ".", "preValidate", "(", "attr", ")", ";", "if", "(", "error", ")", "{", "result", "[", "attr", "]", "=", "error", ";", "}", "}", ")", ";", "return", "_", ".", "isEmpty", "(", "result", ")", "?", "undefined", ":", "result", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "attr", ")", ")", "{", "_", ".", "each", "(", "attr", ",", "function", "(", "value", ",", "key", ")", "{", "error", "=", "self", ".", "preValidate", "(", "key", ",", "value", ")", ";", "if", "(", "error", ")", "{", "result", "[", "key", "]", "=", "error", ";", "}", "}", ")", ";", "return", "_", ".", "isEmpty", "(", "result", ")", "?", "undefined", ":", "result", ";", "}", "else", "{", "if", "(", "_", ".", "isUndefined", "(", "value", ")", "&&", "isNestedModel", "(", "this", ")", ")", "{", "value", "=", "this", ".", "get", "(", "attr", ")", ";", "}", "return", "validateAttr", "(", "this", ",", "value", ",", "attr", ")", ";", "}", "}" ]
Check whether an attribute or a set of attributes are valid. It will default to use the model's current values but you can pass in different values to use in the validation process instead. @param attr {String or Object or Array} Either the name of the attribute, an array containing many attribute names, or on object with attribute name to values @param [value] {Any} a value to use for the attribute value instead of using the model's value. @return undefined if no errors, a validation exception if a single attribute, or an object with attribute name as key and the error as the value @method preValidate
[ "Check", "whether", "an", "attribute", "or", "a", "set", "of", "attributes", "are", "valid", ".", "It", "will", "default", "to", "use", "the", "model", "s", "current", "values", "but", "you", "can", "pass", "in", "different", "values", "to", "use", "in", "the", "validation", "process", "instead", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L3982-L4008
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, fn, model, computed, indices) { return fn.call(this, value, attr, model, computed, indices); }
javascript
function(value, attr, fn, model, computed, indices) { return fn.call(this, value, attr, model, computed, indices); }
[ "function", "(", "value", ",", "attr", ",", "fn", ",", "model", ",", "computed", ",", "indices", ")", "{", "return", "fn", ".", "call", "(", "this", ",", "value", ",", "attr", ",", "model", ",", "computed", ",", "indices", ")", ";", "}" ]
Allows the creation of an inline function that uses the validators context instead of the model context.
[ "Allows", "the", "creation", "of", "an", "inline", "function", "that", "uses", "the", "validators", "context", "instead", "of", "the", "model", "context", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4241-L4243
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, required, model, computed) { var isRequired = _.isFunction(required) ? required.call(model, value, attr, computed) : required; if(!isRequired && !hasValue(value)) { return false; // overrides all other validators } if (isRequired && !hasValue(value)) { return this.format(getMessageKey(this.msgKey, defaultMessages.required), this.formatLabel(attr, model)); } }
javascript
function(value, attr, required, model, computed) { var isRequired = _.isFunction(required) ? required.call(model, value, attr, computed) : required; if(!isRequired && !hasValue(value)) { return false; // overrides all other validators } if (isRequired && !hasValue(value)) { return this.format(getMessageKey(this.msgKey, defaultMessages.required), this.formatLabel(attr, model)); } }
[ "function", "(", "value", ",", "attr", ",", "required", ",", "model", ",", "computed", ")", "{", "var", "isRequired", "=", "_", ".", "isFunction", "(", "required", ")", "?", "required", ".", "call", "(", "model", ",", "value", ",", "attr", ",", "computed", ")", ":", "required", ";", "if", "(", "!", "isRequired", "&&", "!", "hasValue", "(", "value", ")", ")", "{", "return", "false", ";", "// overrides all other validators", "}", "if", "(", "isRequired", "&&", "!", "hasValue", "(", "value", ")", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", ".", "required", ")", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ")", ";", "}", "}" ]
Required validator Validates if the attribute is required or not This can be specified as either a boolean value or a function that returns a boolean value
[ "Required", "validator", "Validates", "if", "the", "attribute", "is", "required", "or", "not", "This", "can", "be", "specified", "as", "either", "a", "boolean", "value", "or", "a", "function", "that", "returns", "a", "boolean", "value" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4248-L4256
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, maxValue, model) { if (!isNumber(value) || value > maxValue) { return this.format(getMessageKey(this.msgKey, defaultMessages.max), this.formatLabel(attr, model), maxValue); } }
javascript
function(value, attr, maxValue, model) { if (!isNumber(value) || value > maxValue) { return this.format(getMessageKey(this.msgKey, defaultMessages.max), this.formatLabel(attr, model), maxValue); } }
[ "function", "(", "value", ",", "attr", ",", "maxValue", ",", "model", ")", "{", "if", "(", "!", "isNumber", "(", "value", ")", "||", "value", ">", "maxValue", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", ".", "max", ")", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ",", "maxValue", ")", ";", "}", "}" ]
Max validator Validates that the value has to be a number and equal to or less than the max value specified
[ "Max", "validator", "Validates", "that", "the", "value", "has", "to", "be", "a", "number", "and", "equal", "to", "or", "less", "than", "the", "max", "value", "specified" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4279-L4283
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, range, model) { if(!isNumber(value) || value < range[0] || value > range[1]) { return this.format(getMessageKey(this.msgKey, defaultMessages.range), this.formatLabel(attr, model), range[0], range[1]); } }
javascript
function(value, attr, range, model) { if(!isNumber(value) || value < range[0] || value > range[1]) { return this.format(getMessageKey(this.msgKey, defaultMessages.range), this.formatLabel(attr, model), range[0], range[1]); } }
[ "function", "(", "value", ",", "attr", ",", "range", ",", "model", ")", "{", "if", "(", "!", "isNumber", "(", "value", ")", "||", "value", "<", "range", "[", "0", "]", "||", "value", ">", "range", "[", "1", "]", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", ".", "range", ")", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ",", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")", ";", "}", "}" ]
Range validator Validates that the value has to be a number and equal to or between the two numbers specified
[ "Range", "validator", "Validates", "that", "the", "value", "has", "to", "be", "a", "number", "and", "equal", "to", "or", "between", "the", "two", "numbers", "specified" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4288-L4292
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, minLength, model) { if (!_.isString(value) || value.length < minLength) { return this.format(getMessageKey(this.msgKey, defaultMessages.minLength), this.formatLabel(attr, model), minLength); } }
javascript
function(value, attr, minLength, model) { if (!_.isString(value) || value.length < minLength) { return this.format(getMessageKey(this.msgKey, defaultMessages.minLength), this.formatLabel(attr, model), minLength); } }
[ "function", "(", "value", ",", "attr", ",", "minLength", ",", "model", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "value", ")", "||", "value", ".", "length", "<", "minLength", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", ".", "minLength", ")", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ",", "minLength", ")", ";", "}", "}" ]
Min length validator Validates that the value has to be a string with length equal to or greater than the min length value specified
[ "Min", "length", "validator", "Validates", "that", "the", "value", "has", "to", "be", "a", "string", "with", "length", "equal", "to", "or", "greater", "than", "the", "min", "length", "value", "specified" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4306-L4310
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, maxLength, model) { if (!_.isString(value) || value.length > maxLength) { return this.format(getMessageKey(this.msgKey, defaultMessages.maxLength), this.formatLabel(attr, model), maxLength); } }
javascript
function(value, attr, maxLength, model) { if (!_.isString(value) || value.length > maxLength) { return this.format(getMessageKey(this.msgKey, defaultMessages.maxLength), this.formatLabel(attr, model), maxLength); } }
[ "function", "(", "value", ",", "attr", ",", "maxLength", ",", "model", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "value", ")", "||", "value", ".", "length", ">", "maxLength", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", ".", "maxLength", ")", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ",", "maxLength", ")", ";", "}", "}" ]
Max length validator Validates that the value has to be a string with length equal to or less than the max length value specified
[ "Max", "length", "validator", "Validates", "that", "the", "value", "has", "to", "be", "a", "string", "with", "length", "equal", "to", "or", "less", "than", "the", "max", "length", "value", "specified" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4315-L4319
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, range, model) { if (!_.isString(value) || value.length < range[0] || value.length > range[1]) { return this.format(getMessageKey(this.msgKey, defaultMessages.rangeLength), this.formatLabel(attr, model), range[0], range[1]); } }
javascript
function(value, attr, range, model) { if (!_.isString(value) || value.length < range[0] || value.length > range[1]) { return this.format(getMessageKey(this.msgKey, defaultMessages.rangeLength), this.formatLabel(attr, model), range[0], range[1]); } }
[ "function", "(", "value", ",", "attr", ",", "range", ",", "model", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "value", ")", "||", "value", ".", "length", "<", "range", "[", "0", "]", "||", "value", ".", "length", ">", "range", "[", "1", "]", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", ".", "rangeLength", ")", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ",", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")", ";", "}", "}" ]
Range length validator Validates that the value has to be a string and equal to or between the two numbers specified
[ "Range", "length", "validator", "Validates", "that", "the", "value", "has", "to", "be", "a", "string", "and", "equal", "to", "or", "between", "the", "two", "numbers", "specified" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4324-L4328
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(value, attr, pattern, model) { if (!hasValue(value) || !value.toString().match(defaultPatterns[pattern] || pattern)) { return this.format(getMessageKey(this.msgKey, defaultMessages[pattern]) || defaultMessages.inlinePattern, this.formatLabel(attr, model), pattern); } }
javascript
function(value, attr, pattern, model) { if (!hasValue(value) || !value.toString().match(defaultPatterns[pattern] || pattern)) { return this.format(getMessageKey(this.msgKey, defaultMessages[pattern]) || defaultMessages.inlinePattern, this.formatLabel(attr, model), pattern); } }
[ "function", "(", "value", ",", "attr", ",", "pattern", ",", "model", ")", "{", "if", "(", "!", "hasValue", "(", "value", ")", "||", "!", "value", ".", "toString", "(", ")", ".", "match", "(", "defaultPatterns", "[", "pattern", "]", "||", "pattern", ")", ")", "{", "return", "this", ".", "format", "(", "getMessageKey", "(", "this", ".", "msgKey", ",", "defaultMessages", "[", "pattern", "]", ")", "||", "defaultMessages", ".", "inlinePattern", ",", "this", ".", "formatLabel", "(", "attr", ",", "model", ")", ",", "pattern", ")", ";", "}", "}" ]
Pattern validator Validates that the value has to match the pattern specified. Can be a regular expression or the name of one of the built in patterns
[ "Pattern", "validator", "Validates", "that", "the", "value", "has", "to", "match", "the", "pattern", "specified", ".", "Can", "be", "a", "regular", "expression", "or", "the", "name", "of", "one", "of", "the", "built", "in", "patterns" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4351-L4355
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(alias, model, copy) { this.__currentObjectModels[alias] = model; this.__updateCache(model); this.resetUpdating(); if (copy) { _.each(this.getMappings(), function(config, mappingAlias) { var modelAliases; if (alias === mappingAlias) { this.__pull(mappingAlias); } if (config.computed) { modelAliases = this.__getModelAliases(mappingAlias); if (_.contains(modelAliases, alias)) { this.__pull(mappingAlias); } } }, this); } }
javascript
function(alias, model, copy) { this.__currentObjectModels[alias] = model; this.__updateCache(model); this.resetUpdating(); if (copy) { _.each(this.getMappings(), function(config, mappingAlias) { var modelAliases; if (alias === mappingAlias) { this.__pull(mappingAlias); } if (config.computed) { modelAliases = this.__getModelAliases(mappingAlias); if (_.contains(modelAliases, alias)) { this.__pull(mappingAlias); } } }, this); } }
[ "function", "(", "alias", ",", "model", ",", "copy", ")", "{", "this", ".", "__currentObjectModels", "[", "alias", "]", "=", "model", ";", "this", ".", "__updateCache", "(", "model", ")", ";", "this", ".", "resetUpdating", "(", ")", ";", "if", "(", "copy", ")", "{", "_", ".", "each", "(", "this", ".", "getMappings", "(", ")", ",", "function", "(", "config", ",", "mappingAlias", ")", "{", "var", "modelAliases", ";", "if", "(", "alias", "===", "mappingAlias", ")", "{", "this", ".", "__pull", "(", "mappingAlias", ")", ";", "}", "if", "(", "config", ".", "computed", ")", "{", "modelAliases", "=", "this", ".", "__getModelAliases", "(", "mappingAlias", ")", ";", "if", "(", "_", ".", "contains", "(", "modelAliases", ",", "alias", ")", ")", "{", "this", ".", "__pull", "(", "mappingAlias", ")", ";", "}", "}", "}", ",", "this", ")", ";", "}", "}" ]
Update or create a binding between an object model and an alias. @method trackModel @param alias {String} the alias/name to bind to. @param model {Backbone Model instance} the model to be bound. Mappings referencing this alias will start applying to this model. @param [copy=false] {Boolean} if true, the form model will perform a pull on any mappings using this alias.
[ "Update", "or", "create", "a", "binding", "between", "an", "object", "model", "and", "an", "alias", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4662-L4680
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(models, copy) { _.each(models, function(instance, alias) { this.trackModel(alias, instance, copy); }, this); }
javascript
function(models, copy) { _.each(models, function(instance, alias) { this.trackModel(alias, instance, copy); }, this); }
[ "function", "(", "models", ",", "copy", ")", "{", "_", ".", "each", "(", "models", ",", "function", "(", "instance", ",", "alias", ")", "{", "this", ".", "trackModel", "(", "alias", ",", "instance", ",", "copy", ")", ";", "}", ",", "this", ")", ";", "}" ]
Binds multiple models to their aliases. @method trackModels @param models {Map from String to Backbone Model instances} A map from alias/name to model to be bound to that alias. @param [copy=false] {Boolean} if true, the form model will perform a pull on any mapping using these models.
[ "Binds", "multiple", "models", "to", "their", "aliases", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4696-L4700
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(aliasOrModel) { var model, alias = this.__findAlias(aliasOrModel); if (alias) { model = this.__currentObjectModels[alias]; delete this.__currentObjectModels[alias]; this.__updateCache(model); } this.resetUpdating(); }
javascript
function(aliasOrModel) { var model, alias = this.__findAlias(aliasOrModel); if (alias) { model = this.__currentObjectModels[alias]; delete this.__currentObjectModels[alias]; this.__updateCache(model); } this.resetUpdating(); }
[ "function", "(", "aliasOrModel", ")", "{", "var", "model", ",", "alias", "=", "this", ".", "__findAlias", "(", "aliasOrModel", ")", ";", "if", "(", "alias", ")", "{", "model", "=", "this", ".", "__currentObjectModels", "[", "alias", "]", ";", "delete", "this", ".", "__currentObjectModels", "[", "alias", "]", ";", "this", ".", "__updateCache", "(", "model", ")", ";", "}", "this", ".", "resetUpdating", "(", ")", ";", "}" ]
Removes the binding between a model alias and a model instance. Effectively stops tracking that model. @method untrackModel @param aliasOrModel {String or Backbone Model instance} If a string is given, it will unset the model using that alias. If a model instance is given, it will unbind whatever alias is currently bound to it.
[ "Removes", "the", "binding", "between", "a", "model", "alias", "and", "a", "model", "instance", ".", "Effectively", "stops", "tracking", "that", "model", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4717-L4726
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { _.each(this.__currentUpdateEvents, function(eventConfig) { this.stopListening(eventConfig.model, eventConfig.eventName); }, this); this.__currentUpdateEvents = []; }
javascript
function() { _.each(this.__currentUpdateEvents, function(eventConfig) { this.stopListening(eventConfig.model, eventConfig.eventName); }, this); this.__currentUpdateEvents = []; }
[ "function", "(", ")", "{", "_", ".", "each", "(", "this", ".", "__currentUpdateEvents", ",", "function", "(", "eventConfig", ")", "{", "this", ".", "stopListening", "(", "eventConfig", ".", "model", ",", "eventConfig", ".", "eventName", ")", ";", "}", ",", "this", ")", ";", "this", ".", "__currentUpdateEvents", "=", "[", "]", ";", "}" ]
This will stop the form model from listening to its object models. @method stopUpdating
[ "This", "will", "stop", "the", "form", "model", "from", "listening", "to", "its", "object", "models", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L4863-L4868
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(computedAlias) { var hasAllModels = true, config = this.getMapping(computedAlias), modelConfigs = []; _.each(this.__getModelAliases(computedAlias), function(modelAlias) { var modelConfig = this.__createModelConfig(modelAlias, config.mapping[modelAlias]); if (modelConfig) { modelConfigs.push(modelConfig); } else { hasAllModels = false; } }, this); return hasAllModels ? modelConfigs : undefined; }
javascript
function(computedAlias) { var hasAllModels = true, config = this.getMapping(computedAlias), modelConfigs = []; _.each(this.__getModelAliases(computedAlias), function(modelAlias) { var modelConfig = this.__createModelConfig(modelAlias, config.mapping[modelAlias]); if (modelConfig) { modelConfigs.push(modelConfig); } else { hasAllModels = false; } }, this); return hasAllModels ? modelConfigs : undefined; }
[ "function", "(", "computedAlias", ")", "{", "var", "hasAllModels", "=", "true", ",", "config", "=", "this", ".", "getMapping", "(", "computedAlias", ")", ",", "modelConfigs", "=", "[", "]", ";", "_", ".", "each", "(", "this", ".", "__getModelAliases", "(", "computedAlias", ")", ",", "function", "(", "modelAlias", ")", "{", "var", "modelConfig", "=", "this", ".", "__createModelConfig", "(", "modelAlias", ",", "config", ".", "mapping", "[", "modelAlias", "]", ")", ";", "if", "(", "modelConfig", ")", "{", "modelConfigs", ".", "push", "(", "modelConfig", ")", ";", "}", "else", "{", "hasAllModels", "=", "false", ";", "}", "}", ",", "this", ")", ";", "return", "hasAllModels", "?", "modelConfigs", ":", "undefined", ";", "}" ]
Repackages a computed mapping to be easier consumed by methods wanting the model mappings tied to the model instances. Returns a list of objects that contain the model instance and the mapping for that model. @method __getComputedModelConfigs @param computedAlias {String} the name/alias used for this computed @return {Array of Objects} a list of objects that contain the model instance under "model" and the mapping for that model under "fields".
[ "Repackages", "a", "computed", "mapping", "to", "be", "easier", "consumed", "by", "methods", "wanting", "the", "model", "mappings", "tied", "to", "the", "model", "instances", ".", "Returns", "a", "list", "of", "objects", "that", "contain", "the", "model", "instance", "and", "the", "mapping", "for", "that", "model", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5019-L5032
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(deferred, options) { var staleModels, formModel = this, responsesSucceeded = 0, responsesFailed = 0, responses = {}, oldValues = {}, models = formModel.getTrackedModels(), numberOfSaves = models.length; // If we're not forcing a save, then throw an error if the models are stale if (!options.force) { staleModels = formModel.checkIfModelsAreStale(); if (staleModels.length > 0) { throw { name: 'Stale data', staleModels: staleModels }; } } // Callback for each response function responseCallback(response, model, success) { // Add response to a hash that will eventually be returned through the promise responses[model.cid] = { success: success, response: response }; // If we have reached the total of number of expected responses, then resolve or reject the promise if (responsesFailed + responsesSucceeded === numberOfSaves) { if (responsesFailed > 0) { // Rollback if any responses have failed if (options.rollback) { _.each(formModel.getTrackedModels(), function(model) { model.set(oldValues[model.cid]); if (responses[model.cid].success) { model.save(); } }); } formModel.trigger('save-fail', responses); deferred.reject(responses); } else { formModel.trigger('save-success', responses); deferred.resolve(responses); } } } // Grab the current values of the object models _.each(models, function(model) { oldValues[model.cid] = formModel.__getTrackedModelFields(model); }); // Push the form model values to the object models formModel.push(); // Call save on each object model _.each(models, function(model) { model.save().fail(function() { responsesFailed++; responseCallback(arguments, model, false); }).done(function() { responsesSucceeded++; responseCallback(arguments, model, true); }); }); }
javascript
function(deferred, options) { var staleModels, formModel = this, responsesSucceeded = 0, responsesFailed = 0, responses = {}, oldValues = {}, models = formModel.getTrackedModels(), numberOfSaves = models.length; // If we're not forcing a save, then throw an error if the models are stale if (!options.force) { staleModels = formModel.checkIfModelsAreStale(); if (staleModels.length > 0) { throw { name: 'Stale data', staleModels: staleModels }; } } // Callback for each response function responseCallback(response, model, success) { // Add response to a hash that will eventually be returned through the promise responses[model.cid] = { success: success, response: response }; // If we have reached the total of number of expected responses, then resolve or reject the promise if (responsesFailed + responsesSucceeded === numberOfSaves) { if (responsesFailed > 0) { // Rollback if any responses have failed if (options.rollback) { _.each(formModel.getTrackedModels(), function(model) { model.set(oldValues[model.cid]); if (responses[model.cid].success) { model.save(); } }); } formModel.trigger('save-fail', responses); deferred.reject(responses); } else { formModel.trigger('save-success', responses); deferred.resolve(responses); } } } // Grab the current values of the object models _.each(models, function(model) { oldValues[model.cid] = formModel.__getTrackedModelFields(model); }); // Push the form model values to the object models formModel.push(); // Call save on each object model _.each(models, function(model) { model.save().fail(function() { responsesFailed++; responseCallback(arguments, model, false); }).done(function() { responsesSucceeded++; responseCallback(arguments, model, true); }); }); }
[ "function", "(", "deferred", ",", "options", ")", "{", "var", "staleModels", ",", "formModel", "=", "this", ",", "responsesSucceeded", "=", "0", ",", "responsesFailed", "=", "0", ",", "responses", "=", "{", "}", ",", "oldValues", "=", "{", "}", ",", "models", "=", "formModel", ".", "getTrackedModels", "(", ")", ",", "numberOfSaves", "=", "models", ".", "length", ";", "// If we're not forcing a save, then throw an error if the models are stale", "if", "(", "!", "options", ".", "force", ")", "{", "staleModels", "=", "formModel", ".", "checkIfModelsAreStale", "(", ")", ";", "if", "(", "staleModels", ".", "length", ">", "0", ")", "{", "throw", "{", "name", ":", "'Stale data'", ",", "staleModels", ":", "staleModels", "}", ";", "}", "}", "// Callback for each response", "function", "responseCallback", "(", "response", ",", "model", ",", "success", ")", "{", "// Add response to a hash that will eventually be returned through the promise", "responses", "[", "model", ".", "cid", "]", "=", "{", "success", ":", "success", ",", "response", ":", "response", "}", ";", "// If we have reached the total of number of expected responses, then resolve or reject the promise", "if", "(", "responsesFailed", "+", "responsesSucceeded", "===", "numberOfSaves", ")", "{", "if", "(", "responsesFailed", ">", "0", ")", "{", "// Rollback if any responses have failed", "if", "(", "options", ".", "rollback", ")", "{", "_", ".", "each", "(", "formModel", ".", "getTrackedModels", "(", ")", ",", "function", "(", "model", ")", "{", "model", ".", "set", "(", "oldValues", "[", "model", ".", "cid", "]", ")", ";", "if", "(", "responses", "[", "model", ".", "cid", "]", ".", "success", ")", "{", "model", ".", "save", "(", ")", ";", "}", "}", ")", ";", "}", "formModel", ".", "trigger", "(", "'save-fail'", ",", "responses", ")", ";", "deferred", ".", "reject", "(", "responses", ")", ";", "}", "else", "{", "formModel", ".", "trigger", "(", "'save-success'", ",", "responses", ")", ";", "deferred", ".", "resolve", "(", "responses", ")", ";", "}", "}", "}", "// Grab the current values of the object models", "_", ".", "each", "(", "models", ",", "function", "(", "model", ")", "{", "oldValues", "[", "model", ".", "cid", "]", "=", "formModel", ".", "__getTrackedModelFields", "(", "model", ")", ";", "}", ")", ";", "// Push the form model values to the object models", "formModel", ".", "push", "(", ")", ";", "// Call save on each object model", "_", ".", "each", "(", "models", ",", "function", "(", "model", ")", "{", "model", ".", "save", "(", ")", ".", "fail", "(", "function", "(", ")", "{", "responsesFailed", "++", ";", "responseCallback", "(", "arguments", ",", "model", ",", "false", ")", ";", "}", ")", ".", "done", "(", "function", "(", ")", "{", "responsesSucceeded", "++", ";", "responseCallback", "(", "arguments", ",", "model", ",", "true", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Pushes the form model values to the object models it is tracking and invokes save on each one. Returns a promise. @param [options] {Object} @param [options.rollback=true] {Boolean} if true, when any object model fails to save, it will revert the object model attributes to the state they were before calling save. NOTE: if there are updates that happen to object models within the timing of this save method, the updates could be lost. @param [options.force=true] {Boolean} if false, the form model will check to see if an update has been made to any object models it is tracking since it's last pull. If any stale data is found, save with throw an exception with attributes: {name: 'Stale data', staleModels: [Array of model cid's]} @return a promise that will either resolve when all the models have successfully saved in which case the context returned is an array of the responses (order determined by first the array of models and then the array of models used by the computed values, normalized), or if any of the saves fail, the promise will be rejected with an array of responses. Note: the size of the failure array will always be one - the first model that failed. This is a side-effect of $.when @private @method __saveToModels
[ "Pushes", "the", "form", "model", "values", "to", "the", "object", "models", "it", "is", "tracking", "and", "invokes", "save", "on", "each", "one", ".", "Returns", "a", "promise", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5050-L5112
train
vecnatechnologies/backbone-torso
torso-bundle.js
responseCallback
function responseCallback(response, model, success) { // Add response to a hash that will eventually be returned through the promise responses[model.cid] = { success: success, response: response }; // If we have reached the total of number of expected responses, then resolve or reject the promise if (responsesFailed + responsesSucceeded === numberOfSaves) { if (responsesFailed > 0) { // Rollback if any responses have failed if (options.rollback) { _.each(formModel.getTrackedModels(), function(model) { model.set(oldValues[model.cid]); if (responses[model.cid].success) { model.save(); } }); } formModel.trigger('save-fail', responses); deferred.reject(responses); } else { formModel.trigger('save-success', responses); deferred.resolve(responses); } } }
javascript
function responseCallback(response, model, success) { // Add response to a hash that will eventually be returned through the promise responses[model.cid] = { success: success, response: response }; // If we have reached the total of number of expected responses, then resolve or reject the promise if (responsesFailed + responsesSucceeded === numberOfSaves) { if (responsesFailed > 0) { // Rollback if any responses have failed if (options.rollback) { _.each(formModel.getTrackedModels(), function(model) { model.set(oldValues[model.cid]); if (responses[model.cid].success) { model.save(); } }); } formModel.trigger('save-fail', responses); deferred.reject(responses); } else { formModel.trigger('save-success', responses); deferred.resolve(responses); } } }
[ "function", "responseCallback", "(", "response", ",", "model", ",", "success", ")", "{", "// Add response to a hash that will eventually be returned through the promise", "responses", "[", "model", ".", "cid", "]", "=", "{", "success", ":", "success", ",", "response", ":", "response", "}", ";", "// If we have reached the total of number of expected responses, then resolve or reject the promise", "if", "(", "responsesFailed", "+", "responsesSucceeded", "===", "numberOfSaves", ")", "{", "if", "(", "responsesFailed", ">", "0", ")", "{", "// Rollback if any responses have failed", "if", "(", "options", ".", "rollback", ")", "{", "_", ".", "each", "(", "formModel", ".", "getTrackedModels", "(", ")", ",", "function", "(", "model", ")", "{", "model", ".", "set", "(", "oldValues", "[", "model", ".", "cid", "]", ")", ";", "if", "(", "responses", "[", "model", ".", "cid", "]", ".", "success", ")", "{", "model", ".", "save", "(", ")", ";", "}", "}", ")", ";", "}", "formModel", ".", "trigger", "(", "'save-fail'", ",", "responses", ")", ";", "deferred", ".", "reject", "(", "responses", ")", ";", "}", "else", "{", "formModel", ".", "trigger", "(", "'save-success'", ",", "responses", ")", ";", "deferred", ".", "resolve", "(", "responses", ")", ";", "}", "}", "}" ]
Callback for each response
[ "Callback", "for", "each", "response" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5070-L5095
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(alias) { var config = this.getMapping(alias); if (config.computed && config.mapping.pull) { this.__invokeComputedPull.call({formModel: this, alias: alias}); } else if (config.computed) { var modelAliases = this.__getModelAliases(alias); _.each(modelAliases, function(modelAlias) { var model = this.getTrackedModel(modelAlias); if (model) { this.__copyFields(config.mapping[modelAlias], this, model); } }, this); } else { var model = this.getTrackedModel(alias); if (model) { this.__copyFields(config.mapping, this, model); } } }
javascript
function(alias) { var config = this.getMapping(alias); if (config.computed && config.mapping.pull) { this.__invokeComputedPull.call({formModel: this, alias: alias}); } else if (config.computed) { var modelAliases = this.__getModelAliases(alias); _.each(modelAliases, function(modelAlias) { var model = this.getTrackedModel(modelAlias); if (model) { this.__copyFields(config.mapping[modelAlias], this, model); } }, this); } else { var model = this.getTrackedModel(alias); if (model) { this.__copyFields(config.mapping, this, model); } } }
[ "function", "(", "alias", ")", "{", "var", "config", "=", "this", ".", "getMapping", "(", "alias", ")", ";", "if", "(", "config", ".", "computed", "&&", "config", ".", "mapping", ".", "pull", ")", "{", "this", ".", "__invokeComputedPull", ".", "call", "(", "{", "formModel", ":", "this", ",", "alias", ":", "alias", "}", ")", ";", "}", "else", "if", "(", "config", ".", "computed", ")", "{", "var", "modelAliases", "=", "this", ".", "__getModelAliases", "(", "alias", ")", ";", "_", ".", "each", "(", "modelAliases", ",", "function", "(", "modelAlias", ")", "{", "var", "model", "=", "this", ".", "getTrackedModel", "(", "modelAlias", ")", ";", "if", "(", "model", ")", "{", "this", ".", "__copyFields", "(", "config", ".", "mapping", "[", "modelAlias", "]", ",", "this", ",", "model", ")", ";", "}", "}", ",", "this", ")", ";", "}", "else", "{", "var", "model", "=", "this", ".", "getTrackedModel", "(", "alias", ")", ";", "if", "(", "model", ")", "{", "this", ".", "__copyFields", "(", "config", ".", "mapping", ",", "this", ",", "model", ")", ";", "}", "}", "}" ]
Pulls in new information from tracked models using the mapping defined by the given alias. This works for both model mappings and computed value mappings @method __pull @param alias {String} the name of the mapping that will be used during the pull @private
[ "Pulls", "in", "new", "information", "from", "tracked", "models", "using", "the", "mapping", "defined", "by", "the", "given", "alias", ".", "This", "works", "for", "both", "model", "mappings", "and", "computed", "value", "mappings" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5121-L5139
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(alias) { var config = this.getMapping(alias); if (config.computed && config.mapping.push) { var models = this.__getComputedModels(alias); if (models) { config.mapping.push.call(this, models); } } else if (config.computed) { var modelAliases = this.__getModelAliases(alias); _.each(modelAliases, function(modelAlias) { var model = this.getTrackedModel(modelAlias); if (model) { this.__copyFields(config.mapping[modelAlias], model, this); } }, this); } else { var model = this.getTrackedModel(alias); if (model) { this.__copyFields(config.mapping, model, this); } } }
javascript
function(alias) { var config = this.getMapping(alias); if (config.computed && config.mapping.push) { var models = this.__getComputedModels(alias); if (models) { config.mapping.push.call(this, models); } } else if (config.computed) { var modelAliases = this.__getModelAliases(alias); _.each(modelAliases, function(modelAlias) { var model = this.getTrackedModel(modelAlias); if (model) { this.__copyFields(config.mapping[modelAlias], model, this); } }, this); } else { var model = this.getTrackedModel(alias); if (model) { this.__copyFields(config.mapping, model, this); } } }
[ "function", "(", "alias", ")", "{", "var", "config", "=", "this", ".", "getMapping", "(", "alias", ")", ";", "if", "(", "config", ".", "computed", "&&", "config", ".", "mapping", ".", "push", ")", "{", "var", "models", "=", "this", ".", "__getComputedModels", "(", "alias", ")", ";", "if", "(", "models", ")", "{", "config", ".", "mapping", ".", "push", ".", "call", "(", "this", ",", "models", ")", ";", "}", "}", "else", "if", "(", "config", ".", "computed", ")", "{", "var", "modelAliases", "=", "this", ".", "__getModelAliases", "(", "alias", ")", ";", "_", ".", "each", "(", "modelAliases", ",", "function", "(", "modelAlias", ")", "{", "var", "model", "=", "this", ".", "getTrackedModel", "(", "modelAlias", ")", ";", "if", "(", "model", ")", "{", "this", ".", "__copyFields", "(", "config", ".", "mapping", "[", "modelAlias", "]", ",", "model", ",", "this", ")", ";", "}", "}", ",", "this", ")", ";", "}", "else", "{", "var", "model", "=", "this", ".", "getTrackedModel", "(", "alias", ")", ";", "if", "(", "model", ")", "{", "this", ".", "__copyFields", "(", "config", ".", "mapping", ",", "model", ",", "this", ")", ";", "}", "}", "}" ]
Pushes form model information to tracked models using the mapping defined by the given alias. This works for both model mappings and computed value mappings @method __push @param alias {String} the name of the mapping that will be used during the push @private
[ "Pushes", "form", "model", "information", "to", "tracked", "models", "using", "the", "mapping", "defined", "by", "the", "given", "alias", ".", "This", "works", "for", "both", "model", "mappings", "and", "computed", "value", "mappings" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5148-L5169
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model) { if (!model) { this.__cache = {}; _.each(this.getTrackedModels(), function(model) { if (model) { this.__updateCache(model); } }, this); } else { this.__cache[model.cid] = this.__generateHashValue(model); } }
javascript
function(model) { if (!model) { this.__cache = {}; _.each(this.getTrackedModels(), function(model) { if (model) { this.__updateCache(model); } }, this); } else { this.__cache[model.cid] = this.__generateHashValue(model); } }
[ "function", "(", "model", ")", "{", "if", "(", "!", "model", ")", "{", "this", ".", "__cache", "=", "{", "}", ";", "_", ".", "each", "(", "this", ".", "getTrackedModels", "(", ")", ",", "function", "(", "model", ")", "{", "if", "(", "model", ")", "{", "this", ".", "__updateCache", "(", "model", ")", ";", "}", "}", ",", "this", ")", ";", "}", "else", "{", "this", ".", "__cache", "[", "model", ".", "cid", "]", "=", "this", ".", "__generateHashValue", "(", "model", ")", ";", "}", "}" ]
Updates the form model's snapshot of the model's attributes to use later @param model {Backbone.Model instance} the object model @param [cache=this.__cache] {Object} if passed an object (can be empty), this method will fill this cache object instead of this form model's __cache field @private @method __updateCache
[ "Updates", "the", "form", "model", "s", "snapshot", "of", "the", "model", "s", "attributes", "to", "use", "later" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5209-L5220
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(val) { var seed; if (_.isArray(val)) { seed = []; } else if (_.isObject(val)) { seed = {}; } else { return val; } return $.extend(true, seed, val); }
javascript
function(val) { var seed; if (_.isArray(val)) { seed = []; } else if (_.isObject(val)) { seed = {}; } else { return val; } return $.extend(true, seed, val); }
[ "function", "(", "val", ")", "{", "var", "seed", ";", "if", "(", "_", ".", "isArray", "(", "val", ")", ")", "{", "seed", "=", "[", "]", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "val", ")", ")", "{", "seed", "=", "{", "}", ";", "}", "else", "{", "return", "val", ";", "}", "return", "$", ".", "extend", "(", "true", ",", "seed", ",", "val", ")", ";", "}" ]
Deep clones the attributes. There should be no functions in the attributes @param val {Object|Array|Basic Data Type} a non-function value @return the clone @private @method __cloneVal
[ "Deep", "clones", "the", "attributes", ".", "There", "should", "be", "no", "functions", "in", "the", "attributes" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5285-L5295
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(options) { var mapping, models, defaultMapping = _.result(this, 'mapping'), defaultModels = _.result(this, 'models'); mapping = options.mapping || defaultMapping; models = options.models || defaultModels; if (mapping) { this.setMappings(mapping, models); } }
javascript
function(options) { var mapping, models, defaultMapping = _.result(this, 'mapping'), defaultModels = _.result(this, 'models'); mapping = options.mapping || defaultMapping; models = options.models || defaultModels; if (mapping) { this.setMappings(mapping, models); } }
[ "function", "(", "options", ")", "{", "var", "mapping", ",", "models", ",", "defaultMapping", "=", "_", ".", "result", "(", "this", ",", "'mapping'", ")", ",", "defaultModels", "=", "_", ".", "result", "(", "this", ",", "'models'", ")", ";", "mapping", "=", "options", ".", "mapping", "||", "defaultMapping", ";", "models", "=", "options", ".", "models", "||", "defaultModels", ";", "if", "(", "mapping", ")", "{", "this", ".", "setMappings", "(", "mapping", ",", "models", ")", ";", "}", "}" ]
Sets the mapping using the form model's default mapping or the options.mappings if available. Also sets the tracked models if the form model's default models or the options.models is provided. @method __initMappings @param [options] {Object} See initialize options: 'mapping' and 'models'. @private
[ "Sets", "the", "mapping", "using", "the", "form", "model", "s", "default", "mapping", "or", "the", "options", ".", "mappings", "if", "available", ".", "Also", "sets", "the", "tracked", "models", "if", "the", "form", "model", "s", "default", "models", "or", "the", "options", ".", "models", "is", "provided", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5365-L5375
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model) { var allFields, fieldsUsed = {}, modelFields = {}, modelConfigs = []; _.each(this.__getAllModelConfigs(), function(modelConfig) { if (modelConfig.model && modelConfig.model.cid === model.cid) { modelConfigs.push(modelConfig); } }); allFields = _.reduce(modelConfigs, function(result, modelConfig) { return result || !modelConfig.fields; }, false); if (allFields) { modelFields = this.__cloneVal(model.attributes); } else { _.each(modelConfigs, function(modelConfig) { _.each(modelConfig.fields, function(field) { if (!fieldsUsed[field]) { fieldsUsed[field] = true; modelFields[field] = this.__cloneVal(model.get(field)); } }, this); }, this); } return modelFields; }
javascript
function(model) { var allFields, fieldsUsed = {}, modelFields = {}, modelConfigs = []; _.each(this.__getAllModelConfigs(), function(modelConfig) { if (modelConfig.model && modelConfig.model.cid === model.cid) { modelConfigs.push(modelConfig); } }); allFields = _.reduce(modelConfigs, function(result, modelConfig) { return result || !modelConfig.fields; }, false); if (allFields) { modelFields = this.__cloneVal(model.attributes); } else { _.each(modelConfigs, function(modelConfig) { _.each(modelConfig.fields, function(field) { if (!fieldsUsed[field]) { fieldsUsed[field] = true; modelFields[field] = this.__cloneVal(model.get(field)); } }, this); }, this); } return modelFields; }
[ "function", "(", "model", ")", "{", "var", "allFields", ",", "fieldsUsed", "=", "{", "}", ",", "modelFields", "=", "{", "}", ",", "modelConfigs", "=", "[", "]", ";", "_", ".", "each", "(", "this", ".", "__getAllModelConfigs", "(", ")", ",", "function", "(", "modelConfig", ")", "{", "if", "(", "modelConfig", ".", "model", "&&", "modelConfig", ".", "model", ".", "cid", "===", "model", ".", "cid", ")", "{", "modelConfigs", ".", "push", "(", "modelConfig", ")", ";", "}", "}", ")", ";", "allFields", "=", "_", ".", "reduce", "(", "modelConfigs", ",", "function", "(", "result", ",", "modelConfig", ")", "{", "return", "result", "||", "!", "modelConfig", ".", "fields", ";", "}", ",", "false", ")", ";", "if", "(", "allFields", ")", "{", "modelFields", "=", "this", ".", "__cloneVal", "(", "model", ".", "attributes", ")", ";", "}", "else", "{", "_", ".", "each", "(", "modelConfigs", ",", "function", "(", "modelConfig", ")", "{", "_", ".", "each", "(", "modelConfig", ".", "fields", ",", "function", "(", "field", ")", "{", "if", "(", "!", "fieldsUsed", "[", "field", "]", ")", "{", "fieldsUsed", "[", "field", "]", "=", "true", ";", "modelFields", "[", "field", "]", "=", "this", ".", "__cloneVal", "(", "model", ".", "get", "(", "field", ")", ")", ";", "}", "}", ",", "this", ")", ";", "}", ",", "this", ")", ";", "}", "return", "modelFields", ";", "}" ]
Returns a map where the keys are the fields that are being tracked on tracked model and values are the with current values of those fields. @param model {Backbone.Model instance} the object model @return {Object} aa map where the keys are the fields that are being tracked on tracked model and values are the with current values of those fields. @private @method __getTrackedModelFields
[ "Returns", "a", "map", "where", "the", "keys", "are", "the", "fields", "that", "are", "being", "tracked", "on", "tracked", "model", "and", "values", "are", "the", "with", "current", "values", "of", "those", "fields", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5386-L5412
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(modelAlias, fields) { var model = this.getTrackedModel(modelAlias); if (model) { return { fields: fields, model: model }; } }
javascript
function(modelAlias, fields) { var model = this.getTrackedModel(modelAlias); if (model) { return { fields: fields, model: model }; } }
[ "function", "(", "modelAlias", ",", "fields", ")", "{", "var", "model", "=", "this", ".", "getTrackedModel", "(", "modelAlias", ")", ";", "if", "(", "model", ")", "{", "return", "{", "fields", ":", "fields", ",", "model", ":", "model", "}", ";", "}", "}" ]
Returns a useful data structure that binds a tracked model to the fields being tracked on a mapping. @method __createModelConfig @param modelAlias @param fields {Array of Strings or undefined} the fields that the model is tracking. Can be undefined if tracking all fields. When creating a model config for a computed mapping, the fields refers to the fields being tracked only for that computed value. @return {Object} a binding between a tracked model and the fields its tracking for a mapping. If no tracked model is bound to the modelAlias, it will return undefined. @private
[ "Returns", "a", "useful", "data", "structure", "that", "binds", "a", "tracked", "model", "to", "the", "fields", "being", "tracked", "on", "a", "mapping", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5424-L5432
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var modelConfigs = []; _.each(this.getMappings(), function(config, alias) { if (config.computed) { var computedModelConfigs = this.__getComputedModelConfigs(alias); if (computedModelConfigs) { modelConfigs = modelConfigs.concat(computedModelConfigs); } } else { var modelConfig = this.__createModelConfig(alias, config.mapping); if (modelConfig) { modelConfigs.push(modelConfig); } } }, this); return modelConfigs; }
javascript
function() { var modelConfigs = []; _.each(this.getMappings(), function(config, alias) { if (config.computed) { var computedModelConfigs = this.__getComputedModelConfigs(alias); if (computedModelConfigs) { modelConfigs = modelConfigs.concat(computedModelConfigs); } } else { var modelConfig = this.__createModelConfig(alias, config.mapping); if (modelConfig) { modelConfigs.push(modelConfig); } } }, this); return modelConfigs; }
[ "function", "(", ")", "{", "var", "modelConfigs", "=", "[", "]", ";", "_", ".", "each", "(", "this", ".", "getMappings", "(", ")", ",", "function", "(", "config", ",", "alias", ")", "{", "if", "(", "config", ".", "computed", ")", "{", "var", "computedModelConfigs", "=", "this", ".", "__getComputedModelConfigs", "(", "alias", ")", ";", "if", "(", "computedModelConfigs", ")", "{", "modelConfigs", "=", "modelConfigs", ".", "concat", "(", "computedModelConfigs", ")", ";", "}", "}", "else", "{", "var", "modelConfig", "=", "this", ".", "__createModelConfig", "(", "alias", ",", "config", ".", "mapping", ")", ";", "if", "(", "modelConfig", ")", "{", "modelConfigs", ".", "push", "(", "modelConfig", ")", ";", "}", "}", "}", ",", "this", ")", ";", "return", "modelConfigs", ";", "}" ]
Returns an array of convenience data structures that bind tracked models to the fields they are tracking for each mapping, including model mappings inside computed mappings. There will be a model config for each tracked model on a computed mapping meaning there can be multiple model configs for the same tracked model. @method __getAllModelConfigs @return {Array} array of convenience data structures that bind tracked models to the fields they are tracking for each mapping, including model mappings inside computed mappings. @private
[ "Returns", "an", "array", "of", "convenience", "data", "structures", "that", "bind", "tracked", "models", "to", "the", "fields", "they", "are", "tracking", "for", "each", "mapping", "including", "model", "mappings", "inside", "computed", "mappings", ".", "There", "will", "be", "a", "model", "config", "for", "each", "tracked", "model", "on", "a", "computed", "mapping", "meaning", "there", "can", "be", "multiple", "model", "configs", "for", "the", "same", "tracked", "model", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5443-L5459
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(args) { View.apply(this, arguments); args = args || {}; var collection = args.collection || this.collection; this.template = args.template || this.template; this.emptyTemplate = args.emptyTemplate || this.emptyTemplate; this.itemView = args.itemView || this.itemView; this.itemContainer = args.itemContainer || this.itemContainer; if (this.template && !this.itemContainer) { throw 'Item container is required when using a template'; } this.modelsToRender = args.modelsToRender || this.modelsToRender; this.__itemContext = args.itemContext || this.__itemContext; this.__modelToViewMap = {}; this.__renderWait = args.renderWait || this.__renderWait; this.__modelId = args.modelId || this.modelId || 'cid'; this.__modelName = args.modelName || this.modelName || 'model'; this.__orderedModelIdList = []; this.__createItemViews(); this.__delayedRender = aggregateRenders(this.__renderWait, this); if (collection) { this.setCollection(collection, true); } this.on('render:after-dom-update', this.__cleanupItemViewsAfterAttachedToParent); }
javascript
function(args) { View.apply(this, arguments); args = args || {}; var collection = args.collection || this.collection; this.template = args.template || this.template; this.emptyTemplate = args.emptyTemplate || this.emptyTemplate; this.itemView = args.itemView || this.itemView; this.itemContainer = args.itemContainer || this.itemContainer; if (this.template && !this.itemContainer) { throw 'Item container is required when using a template'; } this.modelsToRender = args.modelsToRender || this.modelsToRender; this.__itemContext = args.itemContext || this.__itemContext; this.__modelToViewMap = {}; this.__renderWait = args.renderWait || this.__renderWait; this.__modelId = args.modelId || this.modelId || 'cid'; this.__modelName = args.modelName || this.modelName || 'model'; this.__orderedModelIdList = []; this.__createItemViews(); this.__delayedRender = aggregateRenders(this.__renderWait, this); if (collection) { this.setCollection(collection, true); } this.on('render:after-dom-update', this.__cleanupItemViewsAfterAttachedToParent); }
[ "function", "(", "args", ")", "{", "View", ".", "apply", "(", "this", ",", "arguments", ")", ";", "args", "=", "args", "||", "{", "}", ";", "var", "collection", "=", "args", ".", "collection", "||", "this", ".", "collection", ";", "this", ".", "template", "=", "args", ".", "template", "||", "this", ".", "template", ";", "this", ".", "emptyTemplate", "=", "args", ".", "emptyTemplate", "||", "this", ".", "emptyTemplate", ";", "this", ".", "itemView", "=", "args", ".", "itemView", "||", "this", ".", "itemView", ";", "this", ".", "itemContainer", "=", "args", ".", "itemContainer", "||", "this", ".", "itemContainer", ";", "if", "(", "this", ".", "template", "&&", "!", "this", ".", "itemContainer", ")", "{", "throw", "'Item container is required when using a template'", ";", "}", "this", ".", "modelsToRender", "=", "args", ".", "modelsToRender", "||", "this", ".", "modelsToRender", ";", "this", ".", "__itemContext", "=", "args", ".", "itemContext", "||", "this", ".", "__itemContext", ";", "this", ".", "__modelToViewMap", "=", "{", "}", ";", "this", ".", "__renderWait", "=", "args", ".", "renderWait", "||", "this", ".", "__renderWait", ";", "this", ".", "__modelId", "=", "args", ".", "modelId", "||", "this", ".", "modelId", "||", "'cid'", ";", "this", ".", "__modelName", "=", "args", ".", "modelName", "||", "this", ".", "modelName", "||", "'model'", ";", "this", ".", "__orderedModelIdList", "=", "[", "]", ";", "this", ".", "__createItemViews", "(", ")", ";", "this", ".", "__delayedRender", "=", "aggregateRenders", "(", "this", ".", "__renderWait", ",", "this", ")", ";", "if", "(", "collection", ")", "{", "this", ".", "setCollection", "(", "collection", ",", "true", ")", ";", "}", "this", ".", "on", "(", "'render:after-dom-update'", ",", "this", ".", "__cleanupItemViewsAfterAttachedToParent", ")", ";", "}" ]
Constructor for the list view object. @method constructor @param args {Object} - options argument @param args.itemView {Backbone.View definition or Function} - the class definition of the item view. This view will be instantiated for every model returned by modelsToRender(). If a function is passed in, then for each model, this function will be invoked to find the appropriate view class. It takes the model as the only parameter. @param args.collection {Backbone.Collection instance} - The collection that will back this list view. A subclass of list view might provide a default collection. Can be private or public collection @param [args.itemContext] {Object or Function} - object or function that's passed to the item view's during initialization under the name "context". Can be used by the item view during their prepare method. @param [args.template] {HTML Template} - allows a list view to hold it's own HTML like filter buttons, etc. @param [args.itemContainer] {String} - (Required if 'template' is provided, ignored otherwise) name of injection site for list of item views @param [args.emptyTemplate] {HTML Template} - if provided, this template will be shown if the modelsToRender() method returns an empty list. If a itemContainer is provided, the empty template will be rendered there. @param [args.modelsToRender] {Function} - If provided, this function will override the modelsToRender() method with custom functionality. @param [args.renderWait=0] {Number} - If provided, will collect any internally invoked renders (typically through collection events like reset) for a duration specified by renderWait in milliseconds and then calls a single render instead. Helps to remove unnecessary render calls when modifying the collection often. @param [args.modelId='cid'] {'cid' or 'id'} - model property used as identifier for a given model. This property is saved and used to find the corresponding view. @param [args.modelName='model'] {String} - name of the model argument passed to the item view during initialization
[ "Constructor", "for", "the", "list", "view", "object", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5739-L5766
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(collection, preventUpdate) { this.stopListening(this.collection, 'remove', removeItemView); this.stopListening(this.collection, 'add', addItemView); this.stopListening(this.collection, 'sort', this.reorder); this.stopListening(this.collection, 'reset', this.update); this.collection = collection; this.listenTo(this.collection, 'remove', removeItemView); this.listenTo(this.collection, 'add', addItemView); this.listenTo(this.collection, 'sort', this.reorder); this.listenTo(this.collection, 'reset', this.update); if (!preventUpdate) { this.update(); } }
javascript
function(collection, preventUpdate) { this.stopListening(this.collection, 'remove', removeItemView); this.stopListening(this.collection, 'add', addItemView); this.stopListening(this.collection, 'sort', this.reorder); this.stopListening(this.collection, 'reset', this.update); this.collection = collection; this.listenTo(this.collection, 'remove', removeItemView); this.listenTo(this.collection, 'add', addItemView); this.listenTo(this.collection, 'sort', this.reorder); this.listenTo(this.collection, 'reset', this.update); if (!preventUpdate) { this.update(); } }
[ "function", "(", "collection", ",", "preventUpdate", ")", "{", "this", ".", "stopListening", "(", "this", ".", "collection", ",", "'remove'", ",", "removeItemView", ")", ";", "this", ".", "stopListening", "(", "this", ".", "collection", ",", "'add'", ",", "addItemView", ")", ";", "this", ".", "stopListening", "(", "this", ".", "collection", ",", "'sort'", ",", "this", ".", "reorder", ")", ";", "this", ".", "stopListening", "(", "this", ".", "collection", ",", "'reset'", ",", "this", ".", "update", ")", ";", "this", ".", "collection", "=", "collection", ";", "this", ".", "listenTo", "(", "this", ".", "collection", ",", "'remove'", ",", "removeItemView", ")", ";", "this", ".", "listenTo", "(", "this", ".", "collection", ",", "'add'", ",", "addItemView", ")", ";", "this", ".", "listenTo", "(", "this", ".", "collection", ",", "'sort'", ",", "this", ".", "reorder", ")", ";", "this", ".", "listenTo", "(", "this", ".", "collection", ",", "'reset'", ",", "this", ".", "update", ")", ";", "if", "(", "!", "preventUpdate", ")", "{", "this", ".", "update", "(", ")", ";", "}", "}" ]
Sets the collection from which this view generates item views. This method will attach all necessary event listeners to the new collection to auto-generate item views and has the option of removing listeners on a previous collection. It will immediately update child views and re-render if it is necessary - this behavior can be prevented with preventUpdate argument @method setCollection @param collection {Backbone.Collection instance} the new collection that this list view should use. @param preventUpdate {Boolean} if true, the list view will not update the child views nor rerender.
[ "Sets", "the", "collection", "from", "which", "this", "view", "generates", "item", "views", ".", "This", "method", "will", "attach", "all", "necessary", "event", "listeners", "to", "the", "new", "collection", "to", "auto", "-", "generate", "item", "views", "and", "has", "the", "option", "of", "removing", "listeners", "on", "a", "previous", "collection", ".", "It", "will", "immediately", "update", "child", "views", "and", "re", "-", "render", "if", "it", "is", "necessary", "-", "this", "behavior", "can", "be", "prevented", "with", "preventUpdate", "argument" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5778-L5794
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { _.each(this.modelsToRender(), function(model) { var itemView = this.getItemViewFromModel(model); if (itemView) { itemView.delegateEvents(); if (!itemView.__attachedCallbackInvoked && itemView.isAttached()) { itemView.__invokeAttached(); } itemView.activate(); } else { // Shouldn't get here. Item view is missing... } }, this); }
javascript
function() { _.each(this.modelsToRender(), function(model) { var itemView = this.getItemViewFromModel(model); if (itemView) { itemView.delegateEvents(); if (!itemView.__attachedCallbackInvoked && itemView.isAttached()) { itemView.__invokeAttached(); } itemView.activate(); } else { // Shouldn't get here. Item view is missing... } }, this); }
[ "function", "(", ")", "{", "_", ".", "each", "(", "this", ".", "modelsToRender", "(", ")", ",", "function", "(", "model", ")", "{", "var", "itemView", "=", "this", ".", "getItemViewFromModel", "(", "model", ")", ";", "if", "(", "itemView", ")", "{", "itemView", ".", "delegateEvents", "(", ")", ";", "if", "(", "!", "itemView", ".", "__attachedCallbackInvoked", "&&", "itemView", ".", "isAttached", "(", ")", ")", "{", "itemView", ".", "__invokeAttached", "(", ")", ";", "}", "itemView", ".", "activate", "(", ")", ";", "}", "else", "{", "// Shouldn't get here. Item view is missing...", "}", "}", ",", "this", ")", ";", "}" ]
Completes each item view's lifecycle of being attached to a parent. Because the item views are attached in a non-standard way, it's important to make sure that the item views are in the appropriate state after being attached as one fragment. @method __cleanupItemViewsAfterAttachedToParent @private
[ "Completes", "each", "item", "view", "s", "lifecycle", "of", "being", "attached", "to", "a", "parent", ".", "Because", "the", "item", "views", "are", "attached", "in", "a", "non", "-", "standard", "way", "it", "s", "important", "to", "make", "sure", "that", "the", "item", "views", "are", "in", "the", "appropriate", "state", "after", "being", "attached", "as", "one", "fragment", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5826-L5839
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var oldViews = this.getItemViews(); var newViews = this.__createItemViews(); var staleViews = this.__getStaleItemViews(); var sizeOfOldViews = _.size(oldViews); var sizeOfNewViews = _.size(newViews); var sizeOfStaleViews = _.size(staleViews); var sizeOfFinalViews = sizeOfOldViews - sizeOfStaleViews + sizeOfNewViews; var changes = sizeOfNewViews + sizeOfStaleViews; var percentChange = changes / Math.max(sizeOfFinalViews, 1); var fromEmptyToNotEmpty = !sizeOfOldViews && sizeOfNewViews; var fromNotEmptyToEmpty = sizeOfOldViews && sizeOfOldViews === sizeOfStaleViews && !sizeOfNewViews; var threshold = this.updateThreshold || 0.5; var signficantChanges = percentChange >= threshold; if (changes <= 0) { return this.reorder(); } // A switch from empty to not empty or vise versa, needs a new render var renderNeeded = fromEmptyToNotEmpty || fromNotEmptyToEmpty || signficantChanges; if (renderNeeded) { this.__removeStaleItemViews(staleViews); this.__delayedRender(); } else { this.__updateByAddingRemoving(oldViews, newViews, staleViews); } }
javascript
function() { var oldViews = this.getItemViews(); var newViews = this.__createItemViews(); var staleViews = this.__getStaleItemViews(); var sizeOfOldViews = _.size(oldViews); var sizeOfNewViews = _.size(newViews); var sizeOfStaleViews = _.size(staleViews); var sizeOfFinalViews = sizeOfOldViews - sizeOfStaleViews + sizeOfNewViews; var changes = sizeOfNewViews + sizeOfStaleViews; var percentChange = changes / Math.max(sizeOfFinalViews, 1); var fromEmptyToNotEmpty = !sizeOfOldViews && sizeOfNewViews; var fromNotEmptyToEmpty = sizeOfOldViews && sizeOfOldViews === sizeOfStaleViews && !sizeOfNewViews; var threshold = this.updateThreshold || 0.5; var signficantChanges = percentChange >= threshold; if (changes <= 0) { return this.reorder(); } // A switch from empty to not empty or vise versa, needs a new render var renderNeeded = fromEmptyToNotEmpty || fromNotEmptyToEmpty || signficantChanges; if (renderNeeded) { this.__removeStaleItemViews(staleViews); this.__delayedRender(); } else { this.__updateByAddingRemoving(oldViews, newViews, staleViews); } }
[ "function", "(", ")", "{", "var", "oldViews", "=", "this", ".", "getItemViews", "(", ")", ";", "var", "newViews", "=", "this", ".", "__createItemViews", "(", ")", ";", "var", "staleViews", "=", "this", ".", "__getStaleItemViews", "(", ")", ";", "var", "sizeOfOldViews", "=", "_", ".", "size", "(", "oldViews", ")", ";", "var", "sizeOfNewViews", "=", "_", ".", "size", "(", "newViews", ")", ";", "var", "sizeOfStaleViews", "=", "_", ".", "size", "(", "staleViews", ")", ";", "var", "sizeOfFinalViews", "=", "sizeOfOldViews", "-", "sizeOfStaleViews", "+", "sizeOfNewViews", ";", "var", "changes", "=", "sizeOfNewViews", "+", "sizeOfStaleViews", ";", "var", "percentChange", "=", "changes", "/", "Math", ".", "max", "(", "sizeOfFinalViews", ",", "1", ")", ";", "var", "fromEmptyToNotEmpty", "=", "!", "sizeOfOldViews", "&&", "sizeOfNewViews", ";", "var", "fromNotEmptyToEmpty", "=", "sizeOfOldViews", "&&", "sizeOfOldViews", "===", "sizeOfStaleViews", "&&", "!", "sizeOfNewViews", ";", "var", "threshold", "=", "this", ".", "updateThreshold", "||", "0.5", ";", "var", "signficantChanges", "=", "percentChange", ">=", "threshold", ";", "if", "(", "changes", "<=", "0", ")", "{", "return", "this", ".", "reorder", "(", ")", ";", "}", "// A switch from empty to not empty or vise versa, needs a new render", "var", "renderNeeded", "=", "fromEmptyToNotEmpty", "||", "fromNotEmptyToEmpty", "||", "signficantChanges", ";", "if", "(", "renderNeeded", ")", "{", "this", ".", "__removeStaleItemViews", "(", "staleViews", ")", ";", "this", ".", "__delayedRender", "(", ")", ";", "}", "else", "{", "this", ".", "__updateByAddingRemoving", "(", "oldViews", ",", "newViews", ",", "staleViews", ")", ";", "}", "}" ]
Builds any new views, removes stale ones, and re-renders @method update
[ "Builds", "any", "new", "views", "removes", "stale", "ones", "and", "re", "-", "renders" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L5925-L5950
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model, noUpdateToIdList) { var itemView, ItemViewClass = this.itemView; if (!_.isFunction(this.itemView.extend)) { ItemViewClass = this.itemView(model); } itemView = new ItemViewClass(this.__generateItemViewArgs(model)); this.registerTrackedView(itemView, { shared: false }); this.__modelToViewMap[model[this.__modelId]] = itemView.cid; if (!noUpdateToIdList) { this.__updateOrderedModelIdList(); } this.trigger('child-view-added', {model: model, view: itemView}); this.trigger('item-view-added', {model: model, view: itemView}); return itemView; }
javascript
function(model, noUpdateToIdList) { var itemView, ItemViewClass = this.itemView; if (!_.isFunction(this.itemView.extend)) { ItemViewClass = this.itemView(model); } itemView = new ItemViewClass(this.__generateItemViewArgs(model)); this.registerTrackedView(itemView, { shared: false }); this.__modelToViewMap[model[this.__modelId]] = itemView.cid; if (!noUpdateToIdList) { this.__updateOrderedModelIdList(); } this.trigger('child-view-added', {model: model, view: itemView}); this.trigger('item-view-added', {model: model, view: itemView}); return itemView; }
[ "function", "(", "model", ",", "noUpdateToIdList", ")", "{", "var", "itemView", ",", "ItemViewClass", "=", "this", ".", "itemView", ";", "if", "(", "!", "_", ".", "isFunction", "(", "this", ".", "itemView", ".", "extend", ")", ")", "{", "ItemViewClass", "=", "this", ".", "itemView", "(", "model", ")", ";", "}", "itemView", "=", "new", "ItemViewClass", "(", "this", ".", "__generateItemViewArgs", "(", "model", ")", ")", ";", "this", ".", "registerTrackedView", "(", "itemView", ",", "{", "shared", ":", "false", "}", ")", ";", "this", ".", "__modelToViewMap", "[", "model", "[", "this", ".", "__modelId", "]", "]", "=", "itemView", ".", "cid", ";", "if", "(", "!", "noUpdateToIdList", ")", "{", "this", ".", "__updateOrderedModelIdList", "(", ")", ";", "}", "this", ".", "trigger", "(", "'child-view-added'", ",", "{", "model", ":", "model", ",", "view", ":", "itemView", "}", ")", ";", "this", ".", "trigger", "(", "'item-view-added'", ",", "{", "model", ":", "model", ",", "view", ":", "itemView", "}", ")", ";", "return", "itemView", ";", "}" ]
Creates an item view and stores a reference to it @method __createItemView @private @param model {Backbone Model} the model to create the view from @param [noUpdateToIdList=false] if true, the internal order of model ids are not updated @return {Backbone View} the new item view
[ "Creates", "an", "item", "view", "and", "stores", "a", "reference", "to", "it" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6011-L6026
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var staleItemViews = []; var modelsWithViews = _.clone(this.__modelToViewMap); _.each(this.modelsToRender(), function(model) { var itemView = this.getItemViewFromModel(model); if (itemView) { delete modelsWithViews[model[this.__modelId]]; } }, this); _.each(modelsWithViews, function(viewId, modelId) { var itemView = this.getTrackedView(viewId); if (itemView) { staleItemViews.push({ view: itemView, modelId: modelId }); } }, this); return staleItemViews; }
javascript
function() { var staleItemViews = []; var modelsWithViews = _.clone(this.__modelToViewMap); _.each(this.modelsToRender(), function(model) { var itemView = this.getItemViewFromModel(model); if (itemView) { delete modelsWithViews[model[this.__modelId]]; } }, this); _.each(modelsWithViews, function(viewId, modelId) { var itemView = this.getTrackedView(viewId); if (itemView) { staleItemViews.push({ view: itemView, modelId: modelId }); } }, this); return staleItemViews; }
[ "function", "(", ")", "{", "var", "staleItemViews", "=", "[", "]", ";", "var", "modelsWithViews", "=", "_", ".", "clone", "(", "this", ".", "__modelToViewMap", ")", ";", "_", ".", "each", "(", "this", ".", "modelsToRender", "(", ")", ",", "function", "(", "model", ")", "{", "var", "itemView", "=", "this", ".", "getItemViewFromModel", "(", "model", ")", ";", "if", "(", "itemView", ")", "{", "delete", "modelsWithViews", "[", "model", "[", "this", ".", "__modelId", "]", "]", ";", "}", "}", ",", "this", ")", ";", "_", ".", "each", "(", "modelsWithViews", ",", "function", "(", "viewId", ",", "modelId", ")", "{", "var", "itemView", "=", "this", ".", "getTrackedView", "(", "viewId", ")", ";", "if", "(", "itemView", ")", "{", "staleItemViews", ".", "push", "(", "{", "view", ":", "itemView", ",", "modelId", ":", "modelId", "}", ")", ";", "}", "}", ",", "this", ")", ";", "return", "staleItemViews", ";", "}" ]
Gets all item views that have models that are no longer tracked by modelsToRender @method __getStaleItemViews @return {Array} An array of information about stale items. Each object has a 'view' and 'modelId' field @private
[ "Gets", "all", "item", "views", "that", "have", "models", "that", "are", "no", "longer", "tracked", "by", "modelsToRender" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6034-L6050
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(oldViews, newViews, staleViews) { var firstItemViewLeft, injectionSite, view = this, sizeOfOldViews = _.size(oldViews), sizeOfNewViews = _.size(newViews), sizeOfStaleViews = _.size(staleViews); if (view.itemContainer && sizeOfOldViews && sizeOfOldViews == sizeOfStaleViews) { // we removed all the views! injectionSite = $('<span>'); _.first(oldViews).$el.before(injectionSite); } view.__removeStaleItemViews(staleViews); _.each(newViews, function(createdViewInfo, indexOfView) { if (createdViewInfo.indexOfModel === 0) { // need to handle this case uniquely. var replaceMethod; if (!view.itemContainer) { replaceMethod = _.bind(view.$el.prepend, view.$el); } else { if (injectionSite) { replaceMethod = _.bind(injectionSite.replaceWith, injectionSite); } else { var staleModelIdMap = _.indexBy(staleViews, 'modelId'); var firstModelIdLeft = _.find(view.__orderedModelIdList, function(modelId) { return !staleModelIdMap[modelId]; }); firstItemViewLeft = view.getTrackedView(view.__modelToViewMap[firstModelIdLeft]); replaceMethod = _.bind(firstItemViewLeft.$el.prepend, firstItemViewLeft.$el); } } view.attachView(null, createdViewInfo.view, { replaceMethod: replaceMethod, discardInjectionSite: true }); } else { // There will always the view before this one because we are adding new views in order // and we took care of the initial case. _addItemView.call(view, createdViewInfo.view, createdViewInfo.indexOfModel); } }); this.reorder(); }
javascript
function(oldViews, newViews, staleViews) { var firstItemViewLeft, injectionSite, view = this, sizeOfOldViews = _.size(oldViews), sizeOfNewViews = _.size(newViews), sizeOfStaleViews = _.size(staleViews); if (view.itemContainer && sizeOfOldViews && sizeOfOldViews == sizeOfStaleViews) { // we removed all the views! injectionSite = $('<span>'); _.first(oldViews).$el.before(injectionSite); } view.__removeStaleItemViews(staleViews); _.each(newViews, function(createdViewInfo, indexOfView) { if (createdViewInfo.indexOfModel === 0) { // need to handle this case uniquely. var replaceMethod; if (!view.itemContainer) { replaceMethod = _.bind(view.$el.prepend, view.$el); } else { if (injectionSite) { replaceMethod = _.bind(injectionSite.replaceWith, injectionSite); } else { var staleModelIdMap = _.indexBy(staleViews, 'modelId'); var firstModelIdLeft = _.find(view.__orderedModelIdList, function(modelId) { return !staleModelIdMap[modelId]; }); firstItemViewLeft = view.getTrackedView(view.__modelToViewMap[firstModelIdLeft]); replaceMethod = _.bind(firstItemViewLeft.$el.prepend, firstItemViewLeft.$el); } } view.attachView(null, createdViewInfo.view, { replaceMethod: replaceMethod, discardInjectionSite: true }); } else { // There will always the view before this one because we are adding new views in order // and we took care of the initial case. _addItemView.call(view, createdViewInfo.view, createdViewInfo.indexOfModel); } }); this.reorder(); }
[ "function", "(", "oldViews", ",", "newViews", ",", "staleViews", ")", "{", "var", "firstItemViewLeft", ",", "injectionSite", ",", "view", "=", "this", ",", "sizeOfOldViews", "=", "_", ".", "size", "(", "oldViews", ")", ",", "sizeOfNewViews", "=", "_", ".", "size", "(", "newViews", ")", ",", "sizeOfStaleViews", "=", "_", ".", "size", "(", "staleViews", ")", ";", "if", "(", "view", ".", "itemContainer", "&&", "sizeOfOldViews", "&&", "sizeOfOldViews", "==", "sizeOfStaleViews", ")", "{", "// we removed all the views!", "injectionSite", "=", "$", "(", "'<span>'", ")", ";", "_", ".", "first", "(", "oldViews", ")", ".", "$el", ".", "before", "(", "injectionSite", ")", ";", "}", "view", ".", "__removeStaleItemViews", "(", "staleViews", ")", ";", "_", ".", "each", "(", "newViews", ",", "function", "(", "createdViewInfo", ",", "indexOfView", ")", "{", "if", "(", "createdViewInfo", ".", "indexOfModel", "===", "0", ")", "{", "// need to handle this case uniquely.", "var", "replaceMethod", ";", "if", "(", "!", "view", ".", "itemContainer", ")", "{", "replaceMethod", "=", "_", ".", "bind", "(", "view", ".", "$el", ".", "prepend", ",", "view", ".", "$el", ")", ";", "}", "else", "{", "if", "(", "injectionSite", ")", "{", "replaceMethod", "=", "_", ".", "bind", "(", "injectionSite", ".", "replaceWith", ",", "injectionSite", ")", ";", "}", "else", "{", "var", "staleModelIdMap", "=", "_", ".", "indexBy", "(", "staleViews", ",", "'modelId'", ")", ";", "var", "firstModelIdLeft", "=", "_", ".", "find", "(", "view", ".", "__orderedModelIdList", ",", "function", "(", "modelId", ")", "{", "return", "!", "staleModelIdMap", "[", "modelId", "]", ";", "}", ")", ";", "firstItemViewLeft", "=", "view", ".", "getTrackedView", "(", "view", ".", "__modelToViewMap", "[", "firstModelIdLeft", "]", ")", ";", "replaceMethod", "=", "_", ".", "bind", "(", "firstItemViewLeft", ".", "$el", ".", "prepend", ",", "firstItemViewLeft", ".", "$el", ")", ";", "}", "}", "view", ".", "attachView", "(", "null", ",", "createdViewInfo", ".", "view", ",", "{", "replaceMethod", ":", "replaceMethod", ",", "discardInjectionSite", ":", "true", "}", ")", ";", "}", "else", "{", "// There will always the view before this one because we are adding new views in order", "// and we took care of the initial case.", "_addItemView", ".", "call", "(", "view", ",", "createdViewInfo", ".", "view", ",", "createdViewInfo", ".", "indexOfModel", ")", ";", "}", "}", ")", ";", "this", ".", "reorder", "(", ")", ";", "}" ]
Attempts to insert new views and remove stale views individually and correctly reorder all views in an attempt to be faster then a full view re-render @method __updateByAddingRemoving @param oldViews {Array of Views} - correctly ordered list of views before making changes to models to render @param newViews {Array of Views} - the new views created that will be inserted @param staleViews {Array of Views} - the stale views that will be removed
[ "Attempts", "to", "insert", "new", "views", "and", "remove", "stale", "views", "individually", "and", "correctly", "reorder", "all", "views", "in", "an", "attempt", "to", "be", "faster", "then", "a", "full", "view", "re", "-", "render" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6109-L6150
train
vecnatechnologies/backbone-torso
torso-bundle.js
normalizeIds
function normalizeIds(ids) { if (_.isArray(ids)) { // remove any nesting of arrays - it is assumed that the resulting ids will be simple string or number values. ids = _.flatten(ids); // remove any duplicate ids. return _.uniq(ids); } else if (_.isString(ids) || _.isNumber(ids)) { // individual id - convert to array for consistency. return [ids]; } else if (ids && ids.skipObjectRetrieval) { return ids; } }
javascript
function normalizeIds(ids) { if (_.isArray(ids)) { // remove any nesting of arrays - it is assumed that the resulting ids will be simple string or number values. ids = _.flatten(ids); // remove any duplicate ids. return _.uniq(ids); } else if (_.isString(ids) || _.isNumber(ids)) { // individual id - convert to array for consistency. return [ids]; } else if (ids && ids.skipObjectRetrieval) { return ids; } }
[ "function", "normalizeIds", "(", "ids", ")", "{", "if", "(", "_", ".", "isArray", "(", "ids", ")", ")", "{", "// remove any nesting of arrays - it is assumed that the resulting ids will be simple string or number values.", "ids", "=", "_", ".", "flatten", "(", "ids", ")", ";", "// remove any duplicate ids.", "return", "_", ".", "uniq", "(", "ids", ")", ";", "}", "else", "if", "(", "_", ".", "isString", "(", "ids", ")", "||", "_", ".", "isNumber", "(", "ids", ")", ")", "{", "// individual id - convert to array for consistency.", "return", "[", "ids", "]", ";", "}", "else", "if", "(", "ids", "&&", "ids", ".", "skipObjectRetrieval", ")", "{", "return", "ids", ";", "}", "}" ]
Converts string or number values into an array with a single string or number item. If the input is not a string, number, array, or info about the ids then undefined is returned. This is a private helper method used internally by this behavior and is not exposed in any way. @param ids {String|Number|String[]|Number[]|Object} the ids to convert. @param [ids.skipObjectRetrieval] {Boolean} set if this is a meta-info object about the ids. @return {String[]|Number[]|Object} an array of strings or numbers. @private
[ "Converts", "string", "or", "number", "values", "into", "an", "array", "with", "a", "single", "string", "or", "number", "item", ".", "If", "the", "input", "is", "not", "a", "string", "number", "array", "or", "info", "about", "the", "ids", "then", "undefined", "is", "returned", ".", "This", "is", "a", "private", "helper", "method", "used", "internally", "by", "this", "behavior", "and", "is", "not", "exposed", "in", "any", "way", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6247-L6259
train
vecnatechnologies/backbone-torso
torso-bundle.js
undefinedOrNullToEmptyArray
function undefinedOrNullToEmptyArray(valueToConvert) { if (_.isUndefined(valueToConvert) || _.isNull(valueToConvert)) { valueToConvert = []; } return valueToConvert; }
javascript
function undefinedOrNullToEmptyArray(valueToConvert) { if (_.isUndefined(valueToConvert) || _.isNull(valueToConvert)) { valueToConvert = []; } return valueToConvert; }
[ "function", "undefinedOrNullToEmptyArray", "(", "valueToConvert", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "valueToConvert", ")", "||", "_", ".", "isNull", "(", "valueToConvert", ")", ")", "{", "valueToConvert", "=", "[", "]", ";", "}", "return", "valueToConvert", ";", "}" ]
Converts any undefined or null values to an empty array. All other values are left unchanged. @param valueToConvert the value to check for null or undefined. @return {Array|*} either the original value or [] if the valueToConvert is null or undefined.
[ "Converts", "any", "undefined", "or", "null", "values", "to", "an", "empty", "array", ".", "All", "other", "values", "are", "left", "unchanged", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6266-L6271
train
vecnatechnologies/backbone-torso
torso-bundle.js
getNestedProperty
function getNestedProperty(rootObject, propertyString) { propertyString = propertyString.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties propertyString = propertyString.replace(/^\./, ''); // strip a leading dot var propertyStringParts = propertyString.split(PROPERTY_SEPARATOR); return _.reduce(propertyStringParts, function(currentBaseObject, currentPropertyName) { return _.isUndefined(currentBaseObject) ? undefined : currentBaseObject[currentPropertyName]; }, rootObject); }
javascript
function getNestedProperty(rootObject, propertyString) { propertyString = propertyString.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties propertyString = propertyString.replace(/^\./, ''); // strip a leading dot var propertyStringParts = propertyString.split(PROPERTY_SEPARATOR); return _.reduce(propertyStringParts, function(currentBaseObject, currentPropertyName) { return _.isUndefined(currentBaseObject) ? undefined : currentBaseObject[currentPropertyName]; }, rootObject); }
[ "function", "getNestedProperty", "(", "rootObject", ",", "propertyString", ")", "{", "propertyString", "=", "propertyString", ".", "replace", "(", "/", "\\[(\\w+)\\]", "/", "g", ",", "'.$1'", ")", ";", "// convert indexes to properties", "propertyString", "=", "propertyString", ".", "replace", "(", "/", "^\\.", "/", ",", "''", ")", ";", "// strip a leading dot", "var", "propertyStringParts", "=", "propertyString", ".", "split", "(", "PROPERTY_SEPARATOR", ")", ";", "return", "_", ".", "reduce", "(", "propertyStringParts", ",", "function", "(", "currentBaseObject", ",", "currentPropertyName", ")", "{", "return", "_", ".", "isUndefined", "(", "currentBaseObject", ")", "?", "undefined", ":", "currentBaseObject", "[", "currentPropertyName", "]", ";", "}", ",", "rootObject", ")", ";", "}" ]
Gets a nested property from an object, returning undefined if it doesn't exist on any level. @param rootObject {Object} object containing the property to get. @param propertyString {String} string identifying the nested object to retrieve. @return {*} either undefined or the property referenced from the rootObject.
[ "Gets", "a", "nested", "property", "from", "an", "object", "returning", "undefined", "if", "it", "doesn", "t", "exist", "on", "any", "level", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6279-L6286
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var behaviorContext = Behavior.prototype.prepare.apply(this) || {}; behaviorContext.data = this.data.toJSON(); behaviorContext.loading = this.isLoading(); behaviorContext.loadingIds = this.isLoadingIds(); behaviorContext.loadingObjects = this.isLoadingObjects(); return behaviorContext; }
javascript
function() { var behaviorContext = Behavior.prototype.prepare.apply(this) || {}; behaviorContext.data = this.data.toJSON(); behaviorContext.loading = this.isLoading(); behaviorContext.loadingIds = this.isLoadingIds(); behaviorContext.loadingObjects = this.isLoadingObjects(); return behaviorContext; }
[ "function", "(", ")", "{", "var", "behaviorContext", "=", "Behavior", ".", "prototype", ".", "prepare", ".", "apply", "(", "this", ")", "||", "{", "}", ";", "behaviorContext", ".", "data", "=", "this", ".", "data", ".", "toJSON", "(", ")", ";", "behaviorContext", ".", "loading", "=", "this", ".", "isLoading", "(", ")", ";", "behaviorContext", ".", "loadingIds", "=", "this", ".", "isLoadingIds", "(", ")", ";", "behaviorContext", ".", "loadingObjects", "=", "this", ".", "isLoadingObjects", "(", ")", ";", "return", "behaviorContext", ";", "}" ]
Adds the toJSON of the data represented by this behavior to the context. @method prepare @override
[ "Adds", "the", "toJSON", "of", "the", "data", "represented", "by", "this", "behavior", "to", "the", "context", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6553-L6560
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { if (!_.isUndefined(this.ids.property)) { this.stopListeningToIdsPropertyChangeEvent(); var idsPropertyNameAndContext = this.__parseIdsPropertyNameAndIdContainer(); var idContainer = idsPropertyNameAndContext.idContainer; var canListenToEvents = idContainer && _.isFunction(idContainer.on); if (canListenToEvents) { this.__currentContextWithListener = idContainer; this.__currentContextEventName = 'change:' + idsPropertyNameAndContext.idsPropertyName; this.listenTo(this.__currentContextWithListener, this.__currentContextEventName, this.retrieve); this.listenTo(this.__currentContextWithListener, 'fetched:ids', this.retrieve); } } }
javascript
function() { if (!_.isUndefined(this.ids.property)) { this.stopListeningToIdsPropertyChangeEvent(); var idsPropertyNameAndContext = this.__parseIdsPropertyNameAndIdContainer(); var idContainer = idsPropertyNameAndContext.idContainer; var canListenToEvents = idContainer && _.isFunction(idContainer.on); if (canListenToEvents) { this.__currentContextWithListener = idContainer; this.__currentContextEventName = 'change:' + idsPropertyNameAndContext.idsPropertyName; this.listenTo(this.__currentContextWithListener, this.__currentContextEventName, this.retrieve); this.listenTo(this.__currentContextWithListener, 'fetched:ids', this.retrieve); } } }
[ "function", "(", ")", "{", "if", "(", "!", "_", ".", "isUndefined", "(", "this", ".", "ids", ".", "property", ")", ")", "{", "this", ".", "stopListeningToIdsPropertyChangeEvent", "(", ")", ";", "var", "idsPropertyNameAndContext", "=", "this", ".", "__parseIdsPropertyNameAndIdContainer", "(", ")", ";", "var", "idContainer", "=", "idsPropertyNameAndContext", ".", "idContainer", ";", "var", "canListenToEvents", "=", "idContainer", "&&", "_", ".", "isFunction", "(", "idContainer", ".", "on", ")", ";", "if", "(", "canListenToEvents", ")", "{", "this", ".", "__currentContextWithListener", "=", "idContainer", ";", "this", ".", "__currentContextEventName", "=", "'change:'", "+", "idsPropertyNameAndContext", ".", "idsPropertyName", ";", "this", ".", "listenTo", "(", "this", ".", "__currentContextWithListener", ",", "this", ".", "__currentContextEventName", ",", "this", ".", "retrieve", ")", ";", "this", ".", "listenTo", "(", "this", ".", "__currentContextWithListener", ",", "'fetched:ids'", ",", "this", ".", "retrieve", ")", ";", "}", "}", "}" ]
Listens for the change event on the ids property and, if triggered, re-fetches the data based on the new ids. @method listenToIdsPropertyChangeEvent
[ "Listens", "for", "the", "change", "event", "on", "the", "ids", "property", "and", "if", "triggered", "re", "-", "fetches", "the", "data", "based", "on", "the", "new", "ids", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6596-L6609
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { this._undelegateUpdateEvents(); var updateEvents = this.__parseUpdateEvents(); _.each(updateEvents, function(parsedUpdateEvent) { this.listenTo(parsedUpdateEvent.idContainer, parsedUpdateEvent.eventName, this.retrieve); }, this); }
javascript
function() { this._undelegateUpdateEvents(); var updateEvents = this.__parseUpdateEvents(); _.each(updateEvents, function(parsedUpdateEvent) { this.listenTo(parsedUpdateEvent.idContainer, parsedUpdateEvent.eventName, this.retrieve); }, this); }
[ "function", "(", ")", "{", "this", ".", "_undelegateUpdateEvents", "(", ")", ";", "var", "updateEvents", "=", "this", ".", "__parseUpdateEvents", "(", ")", ";", "_", ".", "each", "(", "updateEvents", ",", "function", "(", "parsedUpdateEvent", ")", "{", "this", ".", "listenTo", "(", "parsedUpdateEvent", ".", "idContainer", ",", "parsedUpdateEvent", ".", "eventName", ",", "this", ".", "retrieve", ")", ";", "}", ",", "this", ")", ";", "}" ]
Removes existing listeners and adds new ones for all of the updateEvents configured. @method _delegateUpdateEvents @private
[ "Removes", "existing", "listeners", "and", "adds", "new", "ones", "for", "all", "of", "the", "updateEvents", "configured", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6669-L6675
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var updateEvents = this.__parseUpdateEvents(); _.each(updateEvents, function(parsedUpdateEvent) { this.stopListening(parsedUpdateEvent.idContainer, parsedUpdateEvent.eventName, this.retrieve); }, this); }
javascript
function() { var updateEvents = this.__parseUpdateEvents(); _.each(updateEvents, function(parsedUpdateEvent) { this.stopListening(parsedUpdateEvent.idContainer, parsedUpdateEvent.eventName, this.retrieve); }, this); }
[ "function", "(", ")", "{", "var", "updateEvents", "=", "this", ".", "__parseUpdateEvents", "(", ")", ";", "_", ".", "each", "(", "updateEvents", ",", "function", "(", "parsedUpdateEvent", ")", "{", "this", ".", "stopListening", "(", "parsedUpdateEvent", ".", "idContainer", ",", "parsedUpdateEvent", ".", "eventName", ",", "this", ".", "retrieve", ")", ";", "}", ",", "this", ")", ";", "}" ]
Removes existing event listeners. @method _undelegateEvents @private
[ "Removes", "existing", "event", "listeners", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6682-L6687
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { this.__normalizeAndValidateUpdateEvents(); var updateEvents = _.flatten(_.map(this.updateEvents, this.__parseUpdateEvent, this)); return _.compact(updateEvents); }
javascript
function() { this.__normalizeAndValidateUpdateEvents(); var updateEvents = _.flatten(_.map(this.updateEvents, this.__parseUpdateEvent, this)); return _.compact(updateEvents); }
[ "function", "(", ")", "{", "this", ".", "__normalizeAndValidateUpdateEvents", "(", ")", ";", "var", "updateEvents", "=", "_", ".", "flatten", "(", "_", ".", "map", "(", "this", ".", "updateEvents", ",", "this", ".", "__parseUpdateEvent", ",", "this", ")", ")", ";", "return", "_", ".", "compact", "(", "updateEvents", ")", ";", "}" ]
Parses this.updateEvents configuration. @return {[{ eventName: String, idContainer: Object }]} an array of objects with the event name and idContainer included. @private
[ "Parses", "this", ".", "updateEvents", "configuration", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6694-L6698
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var updateEventsIsArray = _.isArray(this.updateEvents); var updateEventsIsSingleValue = !updateEventsIsArray && (_.isObject(this.updateEvents) || _.isString(this.updateEvents)); var updateEventsIsUndefined = _.isUndefined(this.updateEvents); var updateEventsIsValidType = updateEventsIsArray || updateEventsIsSingleValue || updateEventsIsUndefined; if (updateEventsIsSingleValue) { this.updateEvents = [this.updateEvents]; } if (!updateEventsIsValidType) { throw new Error('Update events are not an array, string or object. Please see parameters for examples of how to define updateEvents. Configured UpdateEvents: ', this.updateEvents); } // Remove any random falsey values (mostly to get rid of undefined events). this.updateEvents = _.compact(this.updateEvents); _.each(this.updateEvents, this.__validUpdateEvent); }
javascript
function() { var updateEventsIsArray = _.isArray(this.updateEvents); var updateEventsIsSingleValue = !updateEventsIsArray && (_.isObject(this.updateEvents) || _.isString(this.updateEvents)); var updateEventsIsUndefined = _.isUndefined(this.updateEvents); var updateEventsIsValidType = updateEventsIsArray || updateEventsIsSingleValue || updateEventsIsUndefined; if (updateEventsIsSingleValue) { this.updateEvents = [this.updateEvents]; } if (!updateEventsIsValidType) { throw new Error('Update events are not an array, string or object. Please see parameters for examples of how to define updateEvents. Configured UpdateEvents: ', this.updateEvents); } // Remove any random falsey values (mostly to get rid of undefined events). this.updateEvents = _.compact(this.updateEvents); _.each(this.updateEvents, this.__validUpdateEvent); }
[ "function", "(", ")", "{", "var", "updateEventsIsArray", "=", "_", ".", "isArray", "(", "this", ".", "updateEvents", ")", ";", "var", "updateEventsIsSingleValue", "=", "!", "updateEventsIsArray", "&&", "(", "_", ".", "isObject", "(", "this", ".", "updateEvents", ")", "||", "_", ".", "isString", "(", "this", ".", "updateEvents", ")", ")", ";", "var", "updateEventsIsUndefined", "=", "_", ".", "isUndefined", "(", "this", ".", "updateEvents", ")", ";", "var", "updateEventsIsValidType", "=", "updateEventsIsArray", "||", "updateEventsIsSingleValue", "||", "updateEventsIsUndefined", ";", "if", "(", "updateEventsIsSingleValue", ")", "{", "this", ".", "updateEvents", "=", "[", "this", ".", "updateEvents", "]", ";", "}", "if", "(", "!", "updateEventsIsValidType", ")", "{", "throw", "new", "Error", "(", "'Update events are not an array, string or object. Please see parameters for examples of how to define updateEvents. Configured UpdateEvents: '", ",", "this", ".", "updateEvents", ")", ";", "}", "// Remove any random falsey values (mostly to get rid of undefined events).", "this", ".", "updateEvents", "=", "_", ".", "compact", "(", "this", ".", "updateEvents", ")", ";", "_", ".", "each", "(", "this", ".", "updateEvents", ",", "this", ".", "__validUpdateEvent", ")", ";", "}" ]
Validates that the updateEvents property is valid and if not throws an error describing why its not valid. @method __normalizeAndValidateUpdateEvents @private
[ "Validates", "that", "the", "updateEvents", "property", "is", "valid", "and", "if", "not", "throws", "an", "error", "describing", "why", "its", "not", "valid", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6797-L6814
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(updateEventConfiguration) { var validStringConfig = _.isString(updateEventConfiguration); var validObjectConfig = _.isObject(updateEventConfiguration) && _.keys(updateEventConfiguration).length > 0; if (!validStringConfig && !validObjectConfig) { throw new Error('Not a valid updateEvent configuration. Update events need to either be strings or objects with a single property: ' + JSON.stringify(updateEventConfiguration)); } }
javascript
function(updateEventConfiguration) { var validStringConfig = _.isString(updateEventConfiguration); var validObjectConfig = _.isObject(updateEventConfiguration) && _.keys(updateEventConfiguration).length > 0; if (!validStringConfig && !validObjectConfig) { throw new Error('Not a valid updateEvent configuration. Update events need to either be strings or objects with a single property: ' + JSON.stringify(updateEventConfiguration)); } }
[ "function", "(", "updateEventConfiguration", ")", "{", "var", "validStringConfig", "=", "_", ".", "isString", "(", "updateEventConfiguration", ")", ";", "var", "validObjectConfig", "=", "_", ".", "isObject", "(", "updateEventConfiguration", ")", "&&", "_", ".", "keys", "(", "updateEventConfiguration", ")", ".", "length", ">", "0", ";", "if", "(", "!", "validStringConfig", "&&", "!", "validObjectConfig", ")", "{", "throw", "new", "Error", "(", "'Not a valid updateEvent configuration. Update events need to either be strings or objects with a single property: '", "+", "JSON", ".", "stringify", "(", "updateEventConfiguration", ")", ")", ";", "}", "}" ]
Validates that the updateEventConfiguration is valid and if not throws an error describing why its not valid. @method __normalizeAndValidateIds @private
[ "Validates", "that", "the", "updateEventConfiguration", "is", "valid", "and", "if", "not", "throws", "an", "error", "describing", "why", "its", "not", "valid", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6821-L6827
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var propertyName = this.ids.property; var propertyNameContainsIdContainer = containsContainerDefinition(propertyName); var hasIdContainerProperty = !_.isUndefined(this.ids.idContainer); var idContainer; if (hasIdContainerProperty) { idContainer = this.__parseIdContainer(); } if (propertyNameContainsIdContainer) { var containerAndDetail = this.__parseContainerDetailString(propertyName); propertyName = containerAndDetail.detail; idContainer = containerAndDetail.idContainer; } if (_.isUndefined(idContainer)) { idContainer = this.view; } return { idsPropertyName: propertyName, idContainer: idContainer }; }
javascript
function() { var propertyName = this.ids.property; var propertyNameContainsIdContainer = containsContainerDefinition(propertyName); var hasIdContainerProperty = !_.isUndefined(this.ids.idContainer); var idContainer; if (hasIdContainerProperty) { idContainer = this.__parseIdContainer(); } if (propertyNameContainsIdContainer) { var containerAndDetail = this.__parseContainerDetailString(propertyName); propertyName = containerAndDetail.detail; idContainer = containerAndDetail.idContainer; } if (_.isUndefined(idContainer)) { idContainer = this.view; } return { idsPropertyName: propertyName, idContainer: idContainer }; }
[ "function", "(", ")", "{", "var", "propertyName", "=", "this", ".", "ids", ".", "property", ";", "var", "propertyNameContainsIdContainer", "=", "containsContainerDefinition", "(", "propertyName", ")", ";", "var", "hasIdContainerProperty", "=", "!", "_", ".", "isUndefined", "(", "this", ".", "ids", ".", "idContainer", ")", ";", "var", "idContainer", ";", "if", "(", "hasIdContainerProperty", ")", "{", "idContainer", "=", "this", ".", "__parseIdContainer", "(", ")", ";", "}", "if", "(", "propertyNameContainsIdContainer", ")", "{", "var", "containerAndDetail", "=", "this", ".", "__parseContainerDetailString", "(", "propertyName", ")", ";", "propertyName", "=", "containerAndDetail", ".", "detail", ";", "idContainer", "=", "containerAndDetail", ".", "idContainer", ";", "}", "if", "(", "_", ".", "isUndefined", "(", "idContainer", ")", ")", "{", "idContainer", "=", "this", ".", "view", ";", "}", "return", "{", "idsPropertyName", ":", "propertyName", ",", "idContainer", ":", "idContainer", "}", ";", "}" ]
Converts the definition into the actual idContainer object and property name to retrieve off of that idContainer. @method __parseIdsPropertyNameAndIdContainer @return {{idsPropertyName: String, idContainer: Object}} the name of the ids property and the actual object to use as the idContainer. @private
[ "Converts", "the", "definition", "into", "the", "actual", "idContainer", "object", "and", "property", "name", "to", "retrieve", "off", "of", "that", "idContainer", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6891-L6915
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var idContainerDefinition = this.ids.idContainer; var idContainer; if (_.isUndefined(idContainerDefinition)) { idContainer = undefined; } else if (_.isFunction(idContainerDefinition)) { var idContainerFxn = _.bind(idContainerDefinition, this); idContainer = idContainerFxn(); } else if (_.isObject(idContainerDefinition)) { idContainer = idContainerDefinition; } else { throw new Error('Invalid idContainer. Not an object or function: ' + JSON.stringify(this.ids)); } return idContainer; }
javascript
function() { var idContainerDefinition = this.ids.idContainer; var idContainer; if (_.isUndefined(idContainerDefinition)) { idContainer = undefined; } else if (_.isFunction(idContainerDefinition)) { var idContainerFxn = _.bind(idContainerDefinition, this); idContainer = idContainerFxn(); } else if (_.isObject(idContainerDefinition)) { idContainer = idContainerDefinition; } else { throw new Error('Invalid idContainer. Not an object or function: ' + JSON.stringify(this.ids)); } return idContainer; }
[ "function", "(", ")", "{", "var", "idContainerDefinition", "=", "this", ".", "ids", ".", "idContainer", ";", "var", "idContainer", ";", "if", "(", "_", ".", "isUndefined", "(", "idContainerDefinition", ")", ")", "{", "idContainer", "=", "undefined", ";", "}", "else", "if", "(", "_", ".", "isFunction", "(", "idContainerDefinition", ")", ")", "{", "var", "idContainerFxn", "=", "_", ".", "bind", "(", "idContainerDefinition", ",", "this", ")", ";", "idContainer", "=", "idContainerFxn", "(", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "idContainerDefinition", ")", ")", "{", "idContainer", "=", "idContainerDefinition", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid idContainer. Not an object or function: '", "+", "JSON", ".", "stringify", "(", "this", ".", "ids", ")", ")", ";", "}", "return", "idContainer", ";", "}" ]
Parses the idContainer property of ids. @return {Object} the idContainer object to apply the properties value to (may not be the final idContainer depending on the property definition). @private
[ "Parses", "the", "idContainer", "property", "of", "ids", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L6922-L6936
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var resultDeferred = $.Deferred(); if (this.isDisposed()) { var rejectArguments = Array.prototype.slice.call(arguments); rejectArguments.push('Data Behavior disposed, aborting.'); resultDeferred.reject.apply(resultDeferred, rejectArguments); } else { resultDeferred.resolve.apply(resultDeferred, arguments); } return resultDeferred.promise(); }
javascript
function() { var resultDeferred = $.Deferred(); if (this.isDisposed()) { var rejectArguments = Array.prototype.slice.call(arguments); rejectArguments.push('Data Behavior disposed, aborting.'); resultDeferred.reject.apply(resultDeferred, rejectArguments); } else { resultDeferred.resolve.apply(resultDeferred, arguments); } return resultDeferred.promise(); }
[ "function", "(", ")", "{", "var", "resultDeferred", "=", "$", ".", "Deferred", "(", ")", ";", "if", "(", "this", ".", "isDisposed", "(", ")", ")", "{", "var", "rejectArguments", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "rejectArguments", ".", "push", "(", "'Data Behavior disposed, aborting.'", ")", ";", "resultDeferred", ".", "reject", ".", "apply", "(", "resultDeferred", ",", "rejectArguments", ")", ";", "}", "else", "{", "resultDeferred", ".", "resolve", ".", "apply", "(", "resultDeferred", ",", "arguments", ")", ";", "}", "return", "resultDeferred", ".", "promise", "(", ")", ";", "}" ]
Rejects the promise chain if this behavior is already disposed. @return {jQuery.Promise} that is resolved if the behavior is not disposed and rejects if the behavior is disposed. @private
[ "Rejects", "the", "promise", "chain", "if", "this", "behavior", "is", "already", "disposed", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L7012-L7022
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(idsResult) { if (_.isEmpty(idsResult) && _.isEmpty(this.data.privateCollection.getTrackedIds())) { return { skipObjectRetrieval: true, forceFetchedEvent: true }; } else { return idsResult; } }
javascript
function(idsResult) { if (_.isEmpty(idsResult) && _.isEmpty(this.data.privateCollection.getTrackedIds())) { return { skipObjectRetrieval: true, forceFetchedEvent: true }; } else { return idsResult; } }
[ "function", "(", "idsResult", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "idsResult", ")", "&&", "_", ".", "isEmpty", "(", "this", ".", "data", ".", "privateCollection", ".", "getTrackedIds", "(", ")", ")", ")", "{", "return", "{", "skipObjectRetrieval", ":", "true", ",", "forceFetchedEvent", ":", "true", "}", ";", "}", "else", "{", "return", "idsResult", ";", "}", "}" ]
Skip retrieving objects if new ids list is empty and existing ids list is empty. @method __skipRetrieveOnEmptyTrackedIdsAndNewIds @param idsResult {Array|Object} @return {Array|Object} either the original idsResult or { skipObjectRetrieval: true, forceFetchedEvent: true } if both the ids retrieved and the current ids are empty. @private
[ "Skip", "retrieving", "objects", "if", "new", "ids", "list", "is", "empty", "and", "existing", "ids", "list", "is", "empty", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L7101-L7107
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var privateCollection = this.privateCollection; if (!this.parentBehavior.returnSingleResult) { return privateCollection.toJSON(); } if (privateCollection.length === 0) { return undefined; } else if (privateCollection.length === 1) { var singleResultModel = privateCollection.at(0); return singleResultModel.toJSON(); } else { throw new Error('Multiple results found, but single result expected: ' + JSON.stringify(privateCollection.toJSON())); } }
javascript
function() { var privateCollection = this.privateCollection; if (!this.parentBehavior.returnSingleResult) { return privateCollection.toJSON(); } if (privateCollection.length === 0) { return undefined; } else if (privateCollection.length === 1) { var singleResultModel = privateCollection.at(0); return singleResultModel.toJSON(); } else { throw new Error('Multiple results found, but single result expected: ' + JSON.stringify(privateCollection.toJSON())); } }
[ "function", "(", ")", "{", "var", "privateCollection", "=", "this", ".", "privateCollection", ";", "if", "(", "!", "this", ".", "parentBehavior", ".", "returnSingleResult", ")", "{", "return", "privateCollection", ".", "toJSON", "(", ")", ";", "}", "if", "(", "privateCollection", ".", "length", "===", "0", ")", "{", "return", "undefined", ";", "}", "else", "if", "(", "privateCollection", ".", "length", "===", "1", ")", "{", "var", "singleResultModel", "=", "privateCollection", ".", "at", "(", "0", ")", ";", "return", "singleResultModel", ".", "toJSON", "(", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Multiple results found, but single result expected: '", "+", "JSON", ".", "stringify", "(", "privateCollection", ".", "toJSON", "(", ")", ")", ")", ";", "}", "}" ]
Get the full data object contents. Either an array if returnSingleResult is false or a single object if it is true. @method toJSON @return {Object|Object[]} containing the full contents of either the collection or model.
[ "Get", "the", "full", "data", "object", "contents", ".", "Either", "an", "array", "if", "returnSingleResult", "is", "false", "or", "a", "single", "object", "if", "it", "is", "true", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L7203-L7217
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(args) { args = args || {}; /* Listen to model validation callbacks */ var FormModelClass = args.FormModelClass || this.FormModelClass || FormModel; this.model = args.model || this.model || (new FormModelClass()); /* Override template */ this.template = args.template || this.template; /* Merge events, fields, bindings, and computeds */ this.events = _.extend({}, this.events || {}, args.events || {}); this.fields = _.extend({}, this.fields || {}, args.fields || {}); this._errors = []; this._success = false; // this._bindings is a snapshot of the original bindings this._bindings = _.extend({}, this.bindings || {}, args.bindings || {}); View.apply(this, arguments); this.resetModelListeners(this.model); }
javascript
function(args) { args = args || {}; /* Listen to model validation callbacks */ var FormModelClass = args.FormModelClass || this.FormModelClass || FormModel; this.model = args.model || this.model || (new FormModelClass()); /* Override template */ this.template = args.template || this.template; /* Merge events, fields, bindings, and computeds */ this.events = _.extend({}, this.events || {}, args.events || {}); this.fields = _.extend({}, this.fields || {}, args.fields || {}); this._errors = []; this._success = false; // this._bindings is a snapshot of the original bindings this._bindings = _.extend({}, this.bindings || {}, args.bindings || {}); View.apply(this, arguments); this.resetModelListeners(this.model); }
[ "function", "(", "args", ")", "{", "args", "=", "args", "||", "{", "}", ";", "/* Listen to model validation callbacks */", "var", "FormModelClass", "=", "args", ".", "FormModelClass", "||", "this", ".", "FormModelClass", "||", "FormModel", ";", "this", ".", "model", "=", "args", ".", "model", "||", "this", ".", "model", "||", "(", "new", "FormModelClass", "(", ")", ")", ";", "/* Override template */", "this", ".", "template", "=", "args", ".", "template", "||", "this", ".", "template", ";", "/* Merge events, fields, bindings, and computeds */", "this", ".", "events", "=", "_", ".", "extend", "(", "{", "}", ",", "this", ".", "events", "||", "{", "}", ",", "args", ".", "events", "||", "{", "}", ")", ";", "this", ".", "fields", "=", "_", ".", "extend", "(", "{", "}", ",", "this", ".", "fields", "||", "{", "}", ",", "args", ".", "fields", "||", "{", "}", ")", ";", "this", ".", "_errors", "=", "[", "]", ";", "this", ".", "_success", "=", "false", ";", "// this._bindings is a snapshot of the original bindings", "this", ".", "_bindings", "=", "_", ".", "extend", "(", "{", "}", ",", "this", ".", "bindings", "||", "{", "}", ",", "args", ".", "bindings", "||", "{", "}", ")", ";", "View", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "resetModelListeners", "(", "this", ".", "model", ")", ";", "}" ]
Validation error hash @private @property _errors @type Object Validation success @private @property _success @type Boolean Stickit bindings hash local backup @private @property _bindings @type Object Handlebars template for form @property template @type HTMLtemplate Backbone events hash @property events @type Object Two-way binding field customization @property fields @type Object Stickit bindings hash @property bindings @type Object The class to be used when instantiating the form model @property FormModelClass @type Torso.FormModel class extension Constructor the form view object. @method constructor @param args {Object} - options argument @param [args.model=new FormModelClass()] {Torso.FormModel} - a form model for binding that defaults to class-level model or instantiates a FormModelClass @param [args.FormModelClass=Torso.FormModel] - the class that will be used as the FormModel. Defaults to a class-level definition or Torso.FormModel if none is provided @param [args.template] {HTML Template} - overrides the template used by this view @param [args.events] {Events Hash} - merge + override the events hash used by this view @param [args.fields] {Field Hash} - merge + override automated two-way binding field hash used by this view @param [args.bindings] {Binding Hash} - merge + override custom epoxy binding hash used by this view
[ "Validation", "error", "hash" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L7394-L7415
train
vecnatechnologies/backbone-torso
torso-bundle.js
function() { var templateContext = View.prototype.prepare.apply(this); templateContext.formErrors = (_.size(this._errors) !== 0) ? this._errors : null; templateContext.formSuccess = this._success; return templateContext; }
javascript
function() { var templateContext = View.prototype.prepare.apply(this); templateContext.formErrors = (_.size(this._errors) !== 0) ? this._errors : null; templateContext.formSuccess = this._success; return templateContext; }
[ "function", "(", ")", "{", "var", "templateContext", "=", "View", ".", "prototype", ".", "prepare", ".", "apply", "(", "this", ")", ";", "templateContext", ".", "formErrors", "=", "(", "_", ".", "size", "(", "this", ".", "_errors", ")", "!==", "0", ")", "?", "this", ".", "_errors", ":", "null", ";", "templateContext", ".", "formSuccess", "=", "this", ".", "_success", ";", "return", "templateContext", ";", "}" ]
Prepare the formview's default render context @method prepare @return {Object} {Object.errors} A hash of field names mapped to error messages {Object.success} A boolean value of true if validation has succeeded
[ "Prepare", "the", "formview", "s", "default", "render", "context" ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L7424-L7429
train
vecnatechnologies/backbone-torso
torso-bundle.js
function(model, stopListening) { if (this.model && stopListening) { this.stopListening(this.model); } this.model = model; this.listenTo(this.model, 'validated:valid', this.valid); this.listenTo(this.model, 'validated:invalid', this.invalid); }
javascript
function(model, stopListening) { if (this.model && stopListening) { this.stopListening(this.model); } this.model = model; this.listenTo(this.model, 'validated:valid', this.valid); this.listenTo(this.model, 'validated:invalid', this.invalid); }
[ "function", "(", "model", ",", "stopListening", ")", "{", "if", "(", "this", ".", "model", "&&", "stopListening", ")", "{", "this", ".", "stopListening", "(", "this", ".", "model", ")", ";", "}", "this", ".", "model", "=", "model", ";", "this", ".", "listenTo", "(", "this", ".", "model", ",", "'validated:valid'", ",", "this", ".", "valid", ")", ";", "this", ".", "listenTo", "(", "this", ".", "model", ",", "'validated:invalid'", ",", "this", ".", "invalid", ")", ";", "}" ]
Resets the form model with the passed in model. Stops listening to current form model and sets up listeners on the new one. @method resetModelListeners @param model {Torso.FormModel} the new form model @param [stopListening=false] {Boolean} if true, it will stop listening to the previous form model
[ "Resets", "the", "form", "model", "with", "the", "passed", "in", "model", ".", "Stops", "listening", "to", "current", "form", "model", "and", "sets", "up", "listeners", "on", "the", "new", "one", "." ]
5afd50da74bd46517dca75d23c10fea594730be2
https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L7449-L7456
train
pebble/clay
src/scripts/components/color.js
deltaE
function deltaE(labA, labB) { var deltaL = labA[0] - labB[0]; var deltaA = labA[1] - labB[1]; var deltaB = labA[2] - labB[2]; return Math.sqrt(Math.pow(deltaL, 2) + Math.pow(deltaA, 2) + Math.pow(deltaB, 2)); }
javascript
function deltaE(labA, labB) { var deltaL = labA[0] - labB[0]; var deltaA = labA[1] - labB[1]; var deltaB = labA[2] - labB[2]; return Math.sqrt(Math.pow(deltaL, 2) + Math.pow(deltaA, 2) + Math.pow(deltaB, 2)); }
[ "function", "deltaE", "(", "labA", ",", "labB", ")", "{", "var", "deltaL", "=", "labA", "[", "0", "]", "-", "labB", "[", "0", "]", ";", "var", "deltaA", "=", "labA", "[", "1", "]", "-", "labB", "[", "1", "]", ";", "var", "deltaB", "=", "labA", "[", "2", "]", "-", "labB", "[", "2", "]", ";", "return", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "deltaL", ",", "2", ")", "+", "Math", ".", "pow", "(", "deltaA", ",", "2", ")", "+", "Math", ".", "pow", "(", "deltaB", ",", "2", ")", ")", ";", "}" ]
Find the perceptual color distance between two LAB colors @param {Array} labA @param {Array} labB @returns {number}
[ "Find", "the", "perceptual", "color", "distance", "between", "two", "LAB", "colors" ]
1bf6db08092ab464974d1762a953ea7cbd24efb8
https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/components/color.js#L102-L110
train
pebble/clay
src/scripts/components/color.js
autoLayout
function autoLayout() { if (!clay.meta.activeWatchInfo || clay.meta.activeWatchInfo.firmware.major === 2 || ['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 && !self.config.allowGray) { return standardLayouts.BLACK_WHITE; } if (['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 && self.config.allowGray) { return standardLayouts.GRAY; } return standardLayouts.COLOR; }
javascript
function autoLayout() { if (!clay.meta.activeWatchInfo || clay.meta.activeWatchInfo.firmware.major === 2 || ['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 && !self.config.allowGray) { return standardLayouts.BLACK_WHITE; } if (['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 && self.config.allowGray) { return standardLayouts.GRAY; } return standardLayouts.COLOR; }
[ "function", "autoLayout", "(", ")", "{", "if", "(", "!", "clay", ".", "meta", ".", "activeWatchInfo", "||", "clay", ".", "meta", ".", "activeWatchInfo", ".", "firmware", ".", "major", "===", "2", "||", "[", "'aplite'", ",", "'diorite'", "]", ".", "indexOf", "(", "clay", ".", "meta", ".", "activeWatchInfo", ".", "platform", ")", ">", "-", "1", "&&", "!", "self", ".", "config", ".", "allowGray", ")", "{", "return", "standardLayouts", ".", "BLACK_WHITE", ";", "}", "if", "(", "[", "'aplite'", ",", "'diorite'", "]", ".", "indexOf", "(", "clay", ".", "meta", ".", "activeWatchInfo", ".", "platform", ")", ">", "-", "1", "&&", "self", ".", "config", ".", "allowGray", ")", "{", "return", "standardLayouts", ".", "GRAY", ";", "}", "return", "standardLayouts", ".", "COLOR", ";", "}" ]
Returns the layout based on the connected watch @returns {Array}
[ "Returns", "the", "layout", "based", "on", "the", "connected", "watch" ]
1bf6db08092ab464974d1762a953ea7cbd24efb8
https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/components/color.js#L116-L130
train
tmcw/stickshift
lib/vega.js
sources
function sources(k) { (src[k] || []).forEach(function(s) { deps[s] = k; sources(s); }); }
javascript
function sources(k) { (src[k] || []).forEach(function(s) { deps[s] = k; sources(s); }); }
[ "function", "sources", "(", "k", ")", "{", "(", "src", "[", "k", "]", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "s", ")", "{", "deps", "[", "s", "]", "=", "k", ";", "sources", "(", "s", ")", ";", "}", ")", ";", "}" ]
collect source data set dependencies
[ "collect", "source", "data", "set", "dependencies" ]
1be06709ca2e1c59d5e5d4b9a0c7b34a46349001
https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/lib/vega.js#L6880-L6882
train
zurb/supercollider
bin/supercollider.js
lib
function lib(val) { var p = path.join(process.cwd(), val); return require(p); }
javascript
function lib(val) { var p = path.join(process.cwd(), val); return require(p); }
[ "function", "lib", "(", "val", ")", "{", "var", "p", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "val", ")", ";", "return", "require", "(", "p", ")", ";", "}" ]
Returns a require'd library from a path
[ "Returns", "a", "require", "d", "library", "from", "a", "path" ]
83cdb9a0e652b448895394d6c83c33b88f44fad2
https://github.com/zurb/supercollider/blob/83cdb9a0e652b448895394d6c83c33b88f44fad2/bin/supercollider.js#L38-L41
train
darul75/ng-prettyjson
src/ng-prettyjson.js
highlight
function highlight(value) { var html = ngPrettyJsonFunctions.syntaxHighlight(value) || ""; html = html .replace(/\{/g, "<span class='sep'>{</span>") .replace(/\}/g, "<span class='sep'>}</span>") .replace(/\[/g, "<span class='sep'>[</span>") .replace(/\]/g, "<span class='sep'>]</span>") .replace(/\,/g, "<span class='sep'>,</span>"); return isDefined(value) ? scope.tmplElt.find('pre').html(html) : scope.tmplElt.find('pre').empty(); }
javascript
function highlight(value) { var html = ngPrettyJsonFunctions.syntaxHighlight(value) || ""; html = html .replace(/\{/g, "<span class='sep'>{</span>") .replace(/\}/g, "<span class='sep'>}</span>") .replace(/\[/g, "<span class='sep'>[</span>") .replace(/\]/g, "<span class='sep'>]</span>") .replace(/\,/g, "<span class='sep'>,</span>"); return isDefined(value) ? scope.tmplElt.find('pre').html(html) : scope.tmplElt.find('pre').empty(); }
[ "function", "highlight", "(", "value", ")", "{", "var", "html", "=", "ngPrettyJsonFunctions", ".", "syntaxHighlight", "(", "value", ")", "||", "\"\"", ";", "html", "=", "html", ".", "replace", "(", "/", "\\{", "/", "g", ",", "\"<span class='sep'>{</span>\"", ")", ".", "replace", "(", "/", "\\}", "/", "g", ",", "\"<span class='sep'>}</span>\"", ")", ".", "replace", "(", "/", "\\[", "/", "g", ",", "\"<span class='sep'>[</span>\"", ")", ".", "replace", "(", "/", "\\]", "/", "g", ",", "\"<span class='sep'>]</span>\"", ")", ".", "replace", "(", "/", "\\,", "/", "g", ",", "\"<span class='sep'>,</span>\"", ")", ";", "return", "isDefined", "(", "value", ")", "?", "scope", ".", "tmplElt", ".", "find", "(", "'pre'", ")", ".", "html", "(", "html", ")", ":", "scope", ".", "tmplElt", ".", "find", "(", "'pre'", ")", ".", "empty", "(", ")", ";", "}" ]
prefer the "json" attribute over the "prettyJson" one. the value on the scope might not be defined yet, so look at the markup.
[ "prefer", "the", "json", "attribute", "over", "the", "prettyJson", "one", ".", "the", "value", "on", "the", "scope", "might", "not", "be", "defined", "yet", "so", "look", "at", "the", "markup", "." ]
2af9bae4d4e9021b5d22e09ffff593b3f5b25f5a
https://github.com/darul75/ng-prettyjson/blob/2af9bae4d4e9021b5d22e09ffff593b3f5b25f5a/src/ng-prettyjson.js#L45-L54
train
pebble/clay
index.js
_populateMeta
function _populateMeta() { self.meta = { activeWatchInfo: Pebble.getActiveWatchInfo && Pebble.getActiveWatchInfo(), accountToken: Pebble.getAccountToken(), watchToken: Pebble.getWatchToken(), userData: deepcopy(options.userData || {}) }; }
javascript
function _populateMeta() { self.meta = { activeWatchInfo: Pebble.getActiveWatchInfo && Pebble.getActiveWatchInfo(), accountToken: Pebble.getAccountToken(), watchToken: Pebble.getWatchToken(), userData: deepcopy(options.userData || {}) }; }
[ "function", "_populateMeta", "(", ")", "{", "self", ".", "meta", "=", "{", "activeWatchInfo", ":", "Pebble", ".", "getActiveWatchInfo", "&&", "Pebble", ".", "getActiveWatchInfo", "(", ")", ",", "accountToken", ":", "Pebble", ".", "getAccountToken", "(", ")", ",", "watchToken", ":", "Pebble", ".", "getWatchToken", "(", ")", ",", "userData", ":", "deepcopy", "(", "options", ".", "userData", "||", "{", "}", ")", "}", ";", "}" ]
Populate the meta with data from the Pebble object. Make sure to run this inside either the "showConfiguration" or "ready" event handler @return {void}
[ "Populate", "the", "meta", "with", "data", "from", "the", "Pebble", "object", ".", "Make", "sure", "to", "run", "this", "inside", "either", "the", "showConfiguration", "or", "ready", "event", "handler" ]
1bf6db08092ab464974d1762a953ea7cbd24efb8
https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/index.js#L50-L57
train
HuddleEng/PhantomXHR
CasperJs/bin/bootstrap.js
initCasperCli
function initCasperCli(casperArgs) { var baseTestsPath = fs.pathJoin(phantom.casperPath, 'tests'); if (!!casperArgs.options.version) { return __terminate(phantom.casperVersion.toString()) } else if (casperArgs.get(0) === "test") { phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js')); phantom.casperTest = true; casperArgs.drop("test"); phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(0)); } else if (casperArgs.get(0) === "selftest") { phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js')); phantom.casperSelfTest = phantom.casperTest = true; casperArgs.options.includes = fs.pathJoin(baseTestsPath, 'selftest.js'); if (casperArgs.args.length <= 1) { casperArgs.args.push(fs.pathJoin(baseTestsPath, 'suites')); } casperArgs.drop("selftest"); phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(1) || fs.dirname(phantom.casperScript)); } else if (casperArgs.args.length === 0 || !!casperArgs.options.help) { return printHelp(); } if (!phantom.casperScript) { phantom.casperScript = casperArgs.get(0); } if (!fs.isFile(phantom.casperScript)) { return __die('Unable to open file: ' + phantom.casperScript); } if (!phantom.casperScriptBaseDir) { var scriptDir = fs.dirname(phantom.casperScript); if (scriptDir === phantom.casperScript) { scriptDir = '.'; } phantom.casperScriptBaseDir = fs.absolute(scriptDir); } // filter out the called script name from casper args casperArgs.drop(phantom.casperScript); }
javascript
function initCasperCli(casperArgs) { var baseTestsPath = fs.pathJoin(phantom.casperPath, 'tests'); if (!!casperArgs.options.version) { return __terminate(phantom.casperVersion.toString()) } else if (casperArgs.get(0) === "test") { phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js')); phantom.casperTest = true; casperArgs.drop("test"); phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(0)); } else if (casperArgs.get(0) === "selftest") { phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js')); phantom.casperSelfTest = phantom.casperTest = true; casperArgs.options.includes = fs.pathJoin(baseTestsPath, 'selftest.js'); if (casperArgs.args.length <= 1) { casperArgs.args.push(fs.pathJoin(baseTestsPath, 'suites')); } casperArgs.drop("selftest"); phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(1) || fs.dirname(phantom.casperScript)); } else if (casperArgs.args.length === 0 || !!casperArgs.options.help) { return printHelp(); } if (!phantom.casperScript) { phantom.casperScript = casperArgs.get(0); } if (!fs.isFile(phantom.casperScript)) { return __die('Unable to open file: ' + phantom.casperScript); } if (!phantom.casperScriptBaseDir) { var scriptDir = fs.dirname(phantom.casperScript); if (scriptDir === phantom.casperScript) { scriptDir = '.'; } phantom.casperScriptBaseDir = fs.absolute(scriptDir); } // filter out the called script name from casper args casperArgs.drop(phantom.casperScript); }
[ "function", "initCasperCli", "(", "casperArgs", ")", "{", "var", "baseTestsPath", "=", "fs", ".", "pathJoin", "(", "phantom", ".", "casperPath", ",", "'tests'", ")", ";", "if", "(", "!", "!", "casperArgs", ".", "options", ".", "version", ")", "{", "return", "__terminate", "(", "phantom", ".", "casperVersion", ".", "toString", "(", ")", ")", "}", "else", "if", "(", "casperArgs", ".", "get", "(", "0", ")", "===", "\"test\"", ")", "{", "phantom", ".", "casperScript", "=", "fs", ".", "absolute", "(", "fs", ".", "pathJoin", "(", "baseTestsPath", ",", "'run.js'", ")", ")", ";", "phantom", ".", "casperTest", "=", "true", ";", "casperArgs", ".", "drop", "(", "\"test\"", ")", ";", "phantom", ".", "casperScriptBaseDir", "=", "fs", ".", "dirname", "(", "casperArgs", ".", "get", "(", "0", ")", ")", ";", "}", "else", "if", "(", "casperArgs", ".", "get", "(", "0", ")", "===", "\"selftest\"", ")", "{", "phantom", ".", "casperScript", "=", "fs", ".", "absolute", "(", "fs", ".", "pathJoin", "(", "baseTestsPath", ",", "'run.js'", ")", ")", ";", "phantom", ".", "casperSelfTest", "=", "phantom", ".", "casperTest", "=", "true", ";", "casperArgs", ".", "options", ".", "includes", "=", "fs", ".", "pathJoin", "(", "baseTestsPath", ",", "'selftest.js'", ")", ";", "if", "(", "casperArgs", ".", "args", ".", "length", "<=", "1", ")", "{", "casperArgs", ".", "args", ".", "push", "(", "fs", ".", "pathJoin", "(", "baseTestsPath", ",", "'suites'", ")", ")", ";", "}", "casperArgs", ".", "drop", "(", "\"selftest\"", ")", ";", "phantom", ".", "casperScriptBaseDir", "=", "fs", ".", "dirname", "(", "casperArgs", ".", "get", "(", "1", ")", "||", "fs", ".", "dirname", "(", "phantom", ".", "casperScript", ")", ")", ";", "}", "else", "if", "(", "casperArgs", ".", "args", ".", "length", "===", "0", "||", "!", "!", "casperArgs", ".", "options", ".", "help", ")", "{", "return", "printHelp", "(", ")", ";", "}", "if", "(", "!", "phantom", ".", "casperScript", ")", "{", "phantom", ".", "casperScript", "=", "casperArgs", ".", "get", "(", "0", ")", ";", "}", "if", "(", "!", "fs", ".", "isFile", "(", "phantom", ".", "casperScript", ")", ")", "{", "return", "__die", "(", "'Unable to open file: '", "+", "phantom", ".", "casperScript", ")", ";", "}", "if", "(", "!", "phantom", ".", "casperScriptBaseDir", ")", "{", "var", "scriptDir", "=", "fs", ".", "dirname", "(", "phantom", ".", "casperScript", ")", ";", "if", "(", "scriptDir", "===", "phantom", ".", "casperScript", ")", "{", "scriptDir", "=", "'.'", ";", "}", "phantom", ".", "casperScriptBaseDir", "=", "fs", ".", "absolute", "(", "scriptDir", ")", ";", "}", "// filter out the called script name from casper args", "casperArgs", ".", "drop", "(", "phantom", ".", "casperScript", ")", ";", "}" ]
Initializes the CasperJS Command Line Interface.
[ "Initializes", "the", "CasperJS", "Command", "Line", "Interface", "." ]
0584a060ca0b6370eae448eda416a66b4ffc6eb6
https://github.com/HuddleEng/PhantomXHR/blob/0584a060ca0b6370eae448eda416a66b4ffc6eb6/CasperJs/bin/bootstrap.js#L227-L268
train
pebble/clay
src/scripts/components/slider.js
setValueDisplay
function setValueDisplay() { var value = self.get().toFixed(self.precision); $value.set('value', value); $valuePad.set('innerHTML', value); }
javascript
function setValueDisplay() { var value = self.get().toFixed(self.precision); $value.set('value', value); $valuePad.set('innerHTML', value); }
[ "function", "setValueDisplay", "(", ")", "{", "var", "value", "=", "self", ".", "get", "(", ")", ".", "toFixed", "(", "self", ".", "precision", ")", ";", "$value", ".", "set", "(", "'value'", ",", "value", ")", ";", "$valuePad", ".", "set", "(", "'innerHTML'", ",", "value", ")", ";", "}" ]
Sets the value display @return {void}
[ "Sets", "the", "value", "display" ]
1bf6db08092ab464974d1762a953ea7cbd24efb8
https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/components/slider.js#L27-L31
train
zurb/supercollider
lib/buildSearch.js
keysInObject
function keysInObject(obj, keys) { for (var i in keys) { if (keys[i] in obj) return true; } return false; }
javascript
function keysInObject(obj, keys) { for (var i in keys) { if (keys[i] in obj) return true; } return false; }
[ "function", "keysInObject", "(", "obj", ",", "keys", ")", "{", "for", "(", "var", "i", "in", "keys", ")", "{", "if", "(", "keys", "[", "i", "]", "in", "obj", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determines if any key in an array exists on an object. @param {object} obj - Object to check for keys. @param {array} keys - Keys to check. @returns {boolean} `true` if any key is found on the object, or `false` if not.
[ "Determines", "if", "any", "key", "in", "an", "array", "exists", "on", "an", "object", "." ]
83cdb9a0e652b448895394d6c83c33b88f44fad2
https://github.com/zurb/supercollider/blob/83cdb9a0e652b448895394d6c83c33b88f44fad2/lib/buildSearch.js#L72-L77
train
pebble/clay
src/scripts/components/select.js
setValueDisplay
function setValueDisplay() { var selectedIndex = self.$manipulatorTarget.get('selectedIndex'); var $options = self.$manipulatorTarget.select('option'); var value = $options[selectedIndex] && $options[selectedIndex].innerHTML; $value.set('innerHTML', value); }
javascript
function setValueDisplay() { var selectedIndex = self.$manipulatorTarget.get('selectedIndex'); var $options = self.$manipulatorTarget.select('option'); var value = $options[selectedIndex] && $options[selectedIndex].innerHTML; $value.set('innerHTML', value); }
[ "function", "setValueDisplay", "(", ")", "{", "var", "selectedIndex", "=", "self", ".", "$manipulatorTarget", ".", "get", "(", "'selectedIndex'", ")", ";", "var", "$options", "=", "self", ".", "$manipulatorTarget", ".", "select", "(", "'option'", ")", ";", "var", "value", "=", "$options", "[", "selectedIndex", "]", "&&", "$options", "[", "selectedIndex", "]", ".", "innerHTML", ";", "$value", ".", "set", "(", "'innerHTML'", ",", "value", ")", ";", "}" ]
Updates the HTML value of the component to match the slected option's label @return {void}
[ "Updates", "the", "HTML", "value", "of", "the", "component", "to", "match", "the", "slected", "option", "s", "label" ]
1bf6db08092ab464974d1762a953ea7cbd24efb8
https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/components/select.js#L23-L28
train
refractproject/minim
lib/ArraySlice.js
coerceElementMatchingCallback
function coerceElementMatchingCallback(value) { // Element Name if (typeof value === 'string') { return element => element.element === value; } // Element Type if (value.constructor && value.extend) { return element => element instanceof value; } return value; }
javascript
function coerceElementMatchingCallback(value) { // Element Name if (typeof value === 'string') { return element => element.element === value; } // Element Type if (value.constructor && value.extend) { return element => element instanceof value; } return value; }
[ "function", "coerceElementMatchingCallback", "(", "value", ")", "{", "// Element Name", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "return", "element", "=>", "element", ".", "element", "===", "value", ";", "}", "// Element Type", "if", "(", "value", ".", "constructor", "&&", "value", ".", "extend", ")", "{", "return", "element", "=>", "element", "instanceof", "value", ";", "}", "return", "value", ";", "}" ]
Coerces an a parameter into a callback for matching elements. This accepts an element name, an element type and returns a callback to match for those elements.
[ "Coerces", "an", "a", "parameter", "into", "a", "callback", "for", "matching", "elements", ".", "This", "accepts", "an", "element", "name", "an", "element", "type", "and", "returns", "a", "callback", "to", "match", "for", "those", "elements", "." ]
7945b8b5e27c5f35e2e5301930c8269edbc284c2
https://github.com/refractproject/minim/blob/7945b8b5e27c5f35e2e5301930c8269edbc284c2/lib/ArraySlice.js#L6-L18
train
AckerApple/ack-angular-fx
bin/src/animations/helper.js
inFromVoid
function inFromVoid(from, to) { return to !== null && to !== 'nofx' && from === 'void' && to !== 'void' ? true : false; }
javascript
function inFromVoid(from, to) { return to !== null && to !== 'nofx' && from === 'void' && to !== 'void' ? true : false; }
[ "function", "inFromVoid", "(", "from", ",", "to", ")", "{", "return", "to", "!==", "null", "&&", "to", "!==", "'nofx'", "&&", "from", "===", "'void'", "&&", "to", "!==", "'void'", "?", "true", ":", "false", ";", "}" ]
used for showing
[ "used", "for", "showing" ]
35308841b3d5a5736063a0cabdb414ced0522747
https://github.com/AckerApple/ack-angular-fx/blob/35308841b3d5a5736063a0cabdb414ced0522747/bin/src/animations/helper.js#L46-L48
train
soney/constraintjs
src/state_machine/cjs_events.js
function(event_type) { var rest_args = arguments.length > 1 ? rest(arguments) : root, // no parent, no filter by default event = new CJSEvent(false, false, function(transition) { var targets = [], timeout_id = false, event_type_val = [], listener = bind(this._fire, this), fsm = transition.getFSM(), from = transition.getFrom(), state_selector = new StateSelector(from), from_state_selector = new TransitionSelector(true, state_selector, new AnyStateSelector()), on_listener = function() { each(event_type_val, function(event_type) { // If the event is 'timeout' if(event_type === timeout_event_type) { // clear the previous timeout if(timeout_id) { cTO(timeout_id); timeout_id = false; } // and set a new one var delay = cjs.get(rest_args[0]); if(!isNumber(delay) || delay < 0) { delay = 0; } timeout_id = sTO(listener, delay); } else { each(targets, function(target) { // otherwise, add the event listener to every one of my targets aEL(target, event_type, listener); }); } }); }, off_listener = function() { each(event_type_val, function(event_type) { each(targets, function(target) { if(event_type === timeout_event_type) { // If the event is 'timeout' if(timeout_id) { cTO(timeout_id); timeout_id = false; } } else { rEL(target, event_type, listener); } }); }); }, live_fn = cjs.liven(function() { off_listener(); event_type_val = split_and_trim(cjs.get(event_type)); // only use DOM elements (or the window) as my target targets = flatten(map(filter(get_dom_array(rest_args), isElementOrWindow), getDOMChildren , true)); // when entering the state, add the event listeners, then remove them when leaving the state fsm .on(state_selector, on_listener) .on(from_state_selector, off_listener); if(fsm.is(from)) { // if the FSM is already in the transition's starting state on_listener(); } }); return live_fn; }); return event; }
javascript
function(event_type) { var rest_args = arguments.length > 1 ? rest(arguments) : root, // no parent, no filter by default event = new CJSEvent(false, false, function(transition) { var targets = [], timeout_id = false, event_type_val = [], listener = bind(this._fire, this), fsm = transition.getFSM(), from = transition.getFrom(), state_selector = new StateSelector(from), from_state_selector = new TransitionSelector(true, state_selector, new AnyStateSelector()), on_listener = function() { each(event_type_val, function(event_type) { // If the event is 'timeout' if(event_type === timeout_event_type) { // clear the previous timeout if(timeout_id) { cTO(timeout_id); timeout_id = false; } // and set a new one var delay = cjs.get(rest_args[0]); if(!isNumber(delay) || delay < 0) { delay = 0; } timeout_id = sTO(listener, delay); } else { each(targets, function(target) { // otherwise, add the event listener to every one of my targets aEL(target, event_type, listener); }); } }); }, off_listener = function() { each(event_type_val, function(event_type) { each(targets, function(target) { if(event_type === timeout_event_type) { // If the event is 'timeout' if(timeout_id) { cTO(timeout_id); timeout_id = false; } } else { rEL(target, event_type, listener); } }); }); }, live_fn = cjs.liven(function() { off_listener(); event_type_val = split_and_trim(cjs.get(event_type)); // only use DOM elements (or the window) as my target targets = flatten(map(filter(get_dom_array(rest_args), isElementOrWindow), getDOMChildren , true)); // when entering the state, add the event listeners, then remove them when leaving the state fsm .on(state_selector, on_listener) .on(from_state_selector, off_listener); if(fsm.is(from)) { // if the FSM is already in the transition's starting state on_listener(); } }); return live_fn; }); return event; }
[ "function", "(", "event_type", ")", "{", "var", "rest_args", "=", "arguments", ".", "length", ">", "1", "?", "rest", "(", "arguments", ")", ":", "root", ",", "// no parent, no filter by default", "event", "=", "new", "CJSEvent", "(", "false", ",", "false", ",", "function", "(", "transition", ")", "{", "var", "targets", "=", "[", "]", ",", "timeout_id", "=", "false", ",", "event_type_val", "=", "[", "]", ",", "listener", "=", "bind", "(", "this", ".", "_fire", ",", "this", ")", ",", "fsm", "=", "transition", ".", "getFSM", "(", ")", ",", "from", "=", "transition", ".", "getFrom", "(", ")", ",", "state_selector", "=", "new", "StateSelector", "(", "from", ")", ",", "from_state_selector", "=", "new", "TransitionSelector", "(", "true", ",", "state_selector", ",", "new", "AnyStateSelector", "(", ")", ")", ",", "on_listener", "=", "function", "(", ")", "{", "each", "(", "event_type_val", ",", "function", "(", "event_type", ")", "{", "// If the event is 'timeout'", "if", "(", "event_type", "===", "timeout_event_type", ")", "{", "// clear the previous timeout", "if", "(", "timeout_id", ")", "{", "cTO", "(", "timeout_id", ")", ";", "timeout_id", "=", "false", ";", "}", "// and set a new one", "var", "delay", "=", "cjs", ".", "get", "(", "rest_args", "[", "0", "]", ")", ";", "if", "(", "!", "isNumber", "(", "delay", ")", "||", "delay", "<", "0", ")", "{", "delay", "=", "0", ";", "}", "timeout_id", "=", "sTO", "(", "listener", ",", "delay", ")", ";", "}", "else", "{", "each", "(", "targets", ",", "function", "(", "target", ")", "{", "// otherwise, add the event listener to every one of my targets", "aEL", "(", "target", ",", "event_type", ",", "listener", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ",", "off_listener", "=", "function", "(", ")", "{", "each", "(", "event_type_val", ",", "function", "(", "event_type", ")", "{", "each", "(", "targets", ",", "function", "(", "target", ")", "{", "if", "(", "event_type", "===", "timeout_event_type", ")", "{", "// If the event is 'timeout'", "if", "(", "timeout_id", ")", "{", "cTO", "(", "timeout_id", ")", ";", "timeout_id", "=", "false", ";", "}", "}", "else", "{", "rEL", "(", "target", ",", "event_type", ",", "listener", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ",", "live_fn", "=", "cjs", ".", "liven", "(", "function", "(", ")", "{", "off_listener", "(", ")", ";", "event_type_val", "=", "split_and_trim", "(", "cjs", ".", "get", "(", "event_type", ")", ")", ";", "// only use DOM elements (or the window) as my target", "targets", "=", "flatten", "(", "map", "(", "filter", "(", "get_dom_array", "(", "rest_args", ")", ",", "isElementOrWindow", ")", ",", "getDOMChildren", ",", "true", ")", ")", ";", "// when entering the state, add the event listeners, then remove them when leaving the state", "fsm", ".", "on", "(", "state_selector", ",", "on_listener", ")", ".", "on", "(", "from_state_selector", ",", "off_listener", ")", ";", "if", "(", "fsm", ".", "is", "(", "from", ")", ")", "{", "// if the FSM is already in the transition's starting state", "on_listener", "(", ")", ";", "}", "}", ")", ";", "return", "live_fn", ";", "}", ")", ";", "return", "event", ";", "}" ]
Create a new event for use in a finite state machine transition @constructs CJSEvent @method cjs.on @param {string} event_type - the type of event to listen for (e.g. mousedown, timeout) @param {element|number} ...targets=window - Any number of target objects to listen to @return {CJSEvent} - An event that can be attached to @example When the window resizes cjs.on("resize") @example When the user clicks `elem1` or `elem2` cjs.on("click", elem1, elem2) @example After 3 seconds cjs.on("timeout", 3000)
[ "Create", "a", "new", "event", "for", "use", "in", "a", "finite", "state", "machine", "transition" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/state_machine/cjs_events.js#L138-L209
train
soney/constraintjs
src/memoize.js
function () { var args = slice.call(arguments), constraint = options.args_map.getOrPut(args, function() { return new Constraint(function () { return getter_fn.apply(options.context, args); }); }); return constraint.get(); }
javascript
function () { var args = slice.call(arguments), constraint = options.args_map.getOrPut(args, function() { return new Constraint(function () { return getter_fn.apply(options.context, args); }); }); return constraint.get(); }
[ "function", "(", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ")", ",", "constraint", "=", "options", ".", "args_map", ".", "getOrPut", "(", "args", ",", "function", "(", ")", "{", "return", "new", "Constraint", "(", "function", "(", ")", "{", "return", "getter_fn", ".", "apply", "(", "options", ".", "context", ",", "args", ")", ";", "}", ")", ";", "}", ")", ";", "return", "constraint", ".", "get", "(", ")", ";", "}" ]
When getting a value either create a constraint or return the existing value
[ "When", "getting", "a", "value", "either", "create", "a", "constraint", "or", "return", "the", "existing", "value" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/memoize.js#L76-L84
train
soney/constraintjs
src/liven.js
function (silent) { if(options.on_destroy) { options.on_destroy.call(options.context, silent); } node.destroy(silent); }
javascript
function (silent) { if(options.on_destroy) { options.on_destroy.call(options.context, silent); } node.destroy(silent); }
[ "function", "(", "silent", ")", "{", "if", "(", "options", ".", "on_destroy", ")", "{", "options", ".", "on_destroy", ".", "call", "(", "options", ".", "context", ",", "silent", ")", ";", "}", "node", ".", "destroy", "(", "silent", ")", ";", "}" ]
Destroy the node and make sure no memory is allocated
[ "Destroy", "the", "node", "and", "make", "sure", "no", "memory", "is", "allocated" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/liven.js#L59-L64
train
soney/constraintjs
src/liven.js
function () { if(paused === true) { paused = false; node.onChangeWithPriority(options.priority, do_get); if(options.run_on_create !== false) { if (constraint_solver.semaphore >= 0) { node.get(false); } else { each(node._changeListeners, constraint_solver.add_in_call_stack, constraint_solver); } } return true; // successfully resumed } return false; }
javascript
function () { if(paused === true) { paused = false; node.onChangeWithPriority(options.priority, do_get); if(options.run_on_create !== false) { if (constraint_solver.semaphore >= 0) { node.get(false); } else { each(node._changeListeners, constraint_solver.add_in_call_stack, constraint_solver); } } return true; // successfully resumed } return false; }
[ "function", "(", ")", "{", "if", "(", "paused", "===", "true", ")", "{", "paused", "=", "false", ";", "node", ".", "onChangeWithPriority", "(", "options", ".", "priority", ",", "do_get", ")", ";", "if", "(", "options", ".", "run_on_create", "!==", "false", ")", "{", "if", "(", "constraint_solver", ".", "semaphore", ">=", "0", ")", "{", "node", ".", "get", "(", "false", ")", ";", "}", "else", "{", "each", "(", "node", ".", "_changeListeners", ",", "constraint_solver", ".", "add_in_call_stack", ",", "constraint_solver", ")", ";", "}", "}", "return", "true", ";", "// successfully resumed", "}", "return", "false", ";", "}" ]
Re-add to the event queue
[ "Re", "-", "add", "to", "the", "event", "queue" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/liven.js#L77-L91
train
soney/constraintjs
src/binding.js
function(options) { this.options = options; this.targets = options.targets; // the DOM nodes var setter = options.setter, // a function that sets the attribute value getter = options.getter, // a function that gets the attribute value init_val = options.init_val, // the value of the attribute before the binding was set curr_value, // used in live fn last_value, // used in live fn old_targets = [], // used in live fn do_update = function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }; this._throttle_delay = false; // Optional throttling to improve performance this._timeout_id = false; // tracks the timeout that helps throttle if(isFunction(init_val)) { // If init_val is a getter, call it on the first element last_value = init_val(get_dom_array(this.targets[0])); } else { // Otherwise, just take it as is last_value = init_val; } this.$live_fn = cjs.liven(function() { curr_value = getter(); // get the value once and inside of live fn to make sure a dependency is added if(this._throttle_delay) { // We shouldn't update values right away if(!this._timeout_id) { // If there isn't any timeout set yet, then set a timeout to delay the call to do update this._timeout_id = sTO(bind(do_update, this), this._throttle_delay); } } else { // we can update the value right away if no throttle delay is set do_update.call(this); } }, { context: this }); }
javascript
function(options) { this.options = options; this.targets = options.targets; // the DOM nodes var setter = options.setter, // a function that sets the attribute value getter = options.getter, // a function that gets the attribute value init_val = options.init_val, // the value of the attribute before the binding was set curr_value, // used in live fn last_value, // used in live fn old_targets = [], // used in live fn do_update = function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }; this._throttle_delay = false; // Optional throttling to improve performance this._timeout_id = false; // tracks the timeout that helps throttle if(isFunction(init_val)) { // If init_val is a getter, call it on the first element last_value = init_val(get_dom_array(this.targets[0])); } else { // Otherwise, just take it as is last_value = init_val; } this.$live_fn = cjs.liven(function() { curr_value = getter(); // get the value once and inside of live fn to make sure a dependency is added if(this._throttle_delay) { // We shouldn't update values right away if(!this._timeout_id) { // If there isn't any timeout set yet, then set a timeout to delay the call to do update this._timeout_id = sTO(bind(do_update, this), this._throttle_delay); } } else { // we can update the value right away if no throttle delay is set do_update.call(this); } }, { context: this }); }
[ "function", "(", "options", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "targets", "=", "options", ".", "targets", ";", "// the DOM nodes", "var", "setter", "=", "options", ".", "setter", ",", "// a function that sets the attribute value", "getter", "=", "options", ".", "getter", ",", "// a function that gets the attribute value", "init_val", "=", "options", ".", "init_val", ",", "// the value of the attribute before the binding was set", "curr_value", ",", "// used in live fn", "last_value", ",", "// used in live fn", "old_targets", "=", "[", "]", ",", "// used in live fn", "do_update", "=", "function", "(", ")", "{", "this", ".", "_timeout_id", "=", "false", ";", "// Make it clear that I don't have a timeout set", "var", "new_targets", "=", "filter", "(", "get_dom_array", "(", "this", ".", "targets", ")", ",", "isAnyElement", ")", ";", "// update the list of targets", "if", "(", "has", "(", "options", ",", "\"onChange\"", ")", ")", "{", "options", ".", "onChange", ".", "call", "(", "this", ",", "curr_value", ",", "last_value", ")", ";", "}", "// For every target, update the attribute", "each", "(", "new_targets", ",", "function", "(", "target", ")", "{", "setter", ".", "call", "(", "this", ",", "target", ",", "curr_value", ",", "last_value", ")", ";", "}", ",", "this", ")", ";", "// track the last value so that next time we call diff", "last_value", "=", "curr_value", ";", "}", ";", "this", ".", "_throttle_delay", "=", "false", ";", "// Optional throttling to improve performance", "this", ".", "_timeout_id", "=", "false", ";", "// tracks the timeout that helps throttle", "if", "(", "isFunction", "(", "init_val", ")", ")", "{", "// If init_val is a getter, call it on the first element", "last_value", "=", "init_val", "(", "get_dom_array", "(", "this", ".", "targets", "[", "0", "]", ")", ")", ";", "}", "else", "{", "// Otherwise, just take it as is", "last_value", "=", "init_val", ";", "}", "this", ".", "$live_fn", "=", "cjs", ".", "liven", "(", "function", "(", ")", "{", "curr_value", "=", "getter", "(", ")", ";", "// get the value once and inside of live fn to make sure a dependency is added", "if", "(", "this", ".", "_throttle_delay", ")", "{", "// We shouldn't update values right away", "if", "(", "!", "this", ".", "_timeout_id", ")", "{", "// If there isn't any timeout set yet, then set a timeout to delay the call to do update", "this", ".", "_timeout_id", "=", "sTO", "(", "bind", "(", "do_update", ",", "this", ")", ",", "this", ".", "_throttle_delay", ")", ";", "}", "}", "else", "{", "// we can update the value right away if no throttle delay is set", "do_update", ".", "call", "(", "this", ")", ";", "}", "}", ",", "{", "context", ":", "this", "}", ")", ";", "}" ]
A binding calls some arbitrary functions passed into options. It is responsible for keeping some aspect of a DOM node in line with a constraint value. For example, it might keep an element's class name in sync with a class_name constraint @private @class cjs.Binding @param {object} options @classdesc Bind a DOM node property to a constraint value
[ "A", "binding", "calls", "some", "arbitrary", "functions", "passed", "into", "options", ".", "It", "is", "responsible", "for", "keeping", "some", "aspect", "of", "a", "DOM", "node", "in", "line", "with", "a", "constraint", "value", ".", "For", "example", "it", "might", "keep", "an", "element", "s", "class", "name", "in", "sync", "with", "a", "class_name", "constraint" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/binding.js#L79-L126
train
soney/constraintjs
src/binding.js
function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }
javascript
function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }
[ "function", "(", ")", "{", "this", ".", "_timeout_id", "=", "false", ";", "// Make it clear that I don't have a timeout set", "var", "new_targets", "=", "filter", "(", "get_dom_array", "(", "this", ".", "targets", ")", ",", "isAnyElement", ")", ";", "// update the list of targets", "if", "(", "has", "(", "options", ",", "\"onChange\"", ")", ")", "{", "options", ".", "onChange", ".", "call", "(", "this", ",", "curr_value", ",", "last_value", ")", ";", "}", "// For every target, update the attribute", "each", "(", "new_targets", ",", "function", "(", "target", ")", "{", "setter", ".", "call", "(", "this", ",", "target", ",", "curr_value", ",", "last_value", ")", ";", "}", ",", "this", ")", ";", "// track the last value so that next time we call diff", "last_value", "=", "curr_value", ";", "}" ]
the DOM nodes
[ "the", "DOM", "nodes" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/binding.js#L88-L103
train
soney/constraintjs
src/map.js
function (infos, silent) { each(infos, function (info) { info.key.destroy(silent); info.value.destroy(silent); info.index.destroy(silent); }); }
javascript
function (infos, silent) { each(infos, function (info) { info.key.destroy(silent); info.value.destroy(silent); info.index.destroy(silent); }); }
[ "function", "(", "infos", ",", "silent", ")", "{", "each", "(", "infos", ",", "function", "(", "info", ")", "{", "info", ".", "key", ".", "destroy", "(", "silent", ")", ";", "info", ".", "value", ".", "destroy", "(", "silent", ")", ";", "info", ".", "index", ".", "destroy", "(", "silent", ")", ";", "}", ")", ";", "}" ]
Deallocate memory from constraints
[ "Deallocate", "memory", "from", "constraints" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/map.js#L370-L376
train
soney/constraintjs
src/map.js
function (index, silent) { var info = this._ordered_values[index]; _destroy_info(this._ordered_values.splice(index, 1), silent); if(silent !== true) { this.$size.invalidate(); } }
javascript
function (index, silent) { var info = this._ordered_values[index]; _destroy_info(this._ordered_values.splice(index, 1), silent); if(silent !== true) { this.$size.invalidate(); } }
[ "function", "(", "index", ",", "silent", ")", "{", "var", "info", "=", "this", ".", "_ordered_values", "[", "index", "]", ";", "_destroy_info", "(", "this", ".", "_ordered_values", ".", "splice", "(", "index", ",", "1", ")", ",", "silent", ")", ";", "if", "(", "silent", "!==", "true", ")", "{", "this", ".", "$size", ".", "invalidate", "(", ")", ";", "}", "}" ]
removes the selected item and destroys its value to deallocate it
[ "removes", "the", "selected", "item", "and", "destroys", "its", "value", "to", "deallocate", "it" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/map.js#L379-L385
train
soney/constraintjs
src/template/cjs_template.js
function(dom_node) { var index = get_template_instance_index(getFirstDOMChild(dom_node)), instance = index >= 0 ? template_instances[index] : false; if(instance) { delete template_instances[index]; instance.destroy(); } return this; }
javascript
function(dom_node) { var index = get_template_instance_index(getFirstDOMChild(dom_node)), instance = index >= 0 ? template_instances[index] : false; if(instance) { delete template_instances[index]; instance.destroy(); } return this; }
[ "function", "(", "dom_node", ")", "{", "var", "index", "=", "get_template_instance_index", "(", "getFirstDOMChild", "(", "dom_node", ")", ")", ",", "instance", "=", "index", ">=", "0", "?", "template_instances", "[", "index", "]", ":", "false", ";", "if", "(", "instance", ")", "{", "delete", "template_instances", "[", "index", "]", ";", "instance", ".", "destroy", "(", ")", ";", "}", "return", "this", ";", "}" ]
Destroy a template instance @method cjs.destroyTemplate @param {dom} node - The dom node created by `createTemplate` @return {boolean} - Whether the template was successfully removed @see cjs.createTemplate @see cjs.pauseTemplate @see cjs.resumeTemplate
[ "Destroy", "a", "template", "instance" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/template/cjs_template.js#L963-L972
train
soney/constraintjs
src/template/cjs_template.js
function(str, context) { return cjs(function() { try { var node = jsep(cjs.get(str)); if(node.type === LITERAL) { return node.value; } else { return get_node_value(node, context, [context]); } } catch(e) { console.error(e); } }); }
javascript
function(str, context) { return cjs(function() { try { var node = jsep(cjs.get(str)); if(node.type === LITERAL) { return node.value; } else { return get_node_value(node, context, [context]); } } catch(e) { console.error(e); } }); }
[ "function", "(", "str", ",", "context", ")", "{", "return", "cjs", "(", "function", "(", ")", "{", "try", "{", "var", "node", "=", "jsep", "(", "cjs", ".", "get", "(", "str", ")", ")", ";", "if", "(", "node", ".", "type", "===", "LITERAL", ")", "{", "return", "node", ".", "value", ";", "}", "else", "{", "return", "get_node_value", "(", "node", ",", "context", ",", "[", "context", "]", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Parses a string and returns a constraint whose value represents the result of `eval`ing that string @method cjs.createParsedConstraint @param {string} str - The string to parse @param {object} context - The context in which to look for variables @return {cjs.Cosntraint} - Whether the template was successfully resumed @example Creating a parsed constraint `x` var a = cjs(1); var x = cjs.createParsedConstraint("a+b", {a: a, b: cjs(2)}) x.get(); // 3 a.set(2); x.get(); // 4
[ "Parses", "a", "string", "and", "returns", "a", "constraint", "whose", "value", "represents", "the", "result", "of", "eval", "ing", "that", "string" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/template/cjs_template.js#L1022-L1036
train
nteract/kernelspecs
lib/traverse.js
promisify
function promisify(f, args) { return new Promise((resolve, reject) => f.apply(this, args.concat((err, x) => err ? reject(err) : resolve(x)))); }
javascript
function promisify(f, args) { return new Promise((resolve, reject) => f.apply(this, args.concat((err, x) => err ? reject(err) : resolve(x)))); }
[ "function", "promisify", "(", "f", ",", "args", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "f", ".", "apply", "(", "this", ",", "args", ".", "concat", "(", "(", "err", ",", "x", ")", "=>", "err", "?", "reject", "(", "err", ")", ":", "resolve", "(", "x", ")", ")", ")", ")", ";", "}" ]
Converts a callback style call to a Promise @param {function} f a node style function that accepts a callback @param {Object[]} args arguments to pass to the function when invoking it @return {Promise<Object>} object returned by the function
[ "Converts", "a", "callback", "style", "call", "to", "a", "Promise" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L11-L13
train
nteract/kernelspecs
lib/traverse.js
getKernelResources
function getKernelResources(kernelInfo) { return promisify(fs.readdir, [kernelInfo.resourceDir]).then(files => { const kernelJSONIndex = files.indexOf('kernel.json'); if (kernelJSONIndex === -1) { throw new Error('kernel.json not found'); } return promisify(fs.readFile, [path.join(kernelInfo.resourceDir, 'kernel.json')]).then(data => ({ name: kernelInfo.name, files: files.map(x => path.join(kernelInfo.resourceDir, x)), resources_dir: kernelInfo.resourceDir, // eslint-disable-line camelcase spec: JSON.parse(data), })); }); }
javascript
function getKernelResources(kernelInfo) { return promisify(fs.readdir, [kernelInfo.resourceDir]).then(files => { const kernelJSONIndex = files.indexOf('kernel.json'); if (kernelJSONIndex === -1) { throw new Error('kernel.json not found'); } return promisify(fs.readFile, [path.join(kernelInfo.resourceDir, 'kernel.json')]).then(data => ({ name: kernelInfo.name, files: files.map(x => path.join(kernelInfo.resourceDir, x)), resources_dir: kernelInfo.resourceDir, // eslint-disable-line camelcase spec: JSON.parse(data), })); }); }
[ "function", "getKernelResources", "(", "kernelInfo", ")", "{", "return", "promisify", "(", "fs", ".", "readdir", ",", "[", "kernelInfo", ".", "resourceDir", "]", ")", ".", "then", "(", "files", "=>", "{", "const", "kernelJSONIndex", "=", "files", ".", "indexOf", "(", "'kernel.json'", ")", ";", "if", "(", "kernelJSONIndex", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "'kernel.json not found'", ")", ";", "}", "return", "promisify", "(", "fs", ".", "readFile", ",", "[", "path", ".", "join", "(", "kernelInfo", ".", "resourceDir", ",", "'kernel.json'", ")", "]", ")", ".", "then", "(", "data", "=>", "(", "{", "name", ":", "kernelInfo", ".", "name", ",", "files", ":", "files", ".", "map", "(", "x", "=>", "path", ".", "join", "(", "kernelInfo", ".", "resourceDir", ",", "x", ")", ")", ",", "resources_dir", ":", "kernelInfo", ".", "resourceDir", ",", "// eslint-disable-line camelcase", "spec", ":", "JSON", ".", "parse", "(", "data", ")", ",", "}", ")", ")", ";", "}", ")", ";", "}" ]
Get a kernel resources object @param {Object} kernelInfo description of a kernel @param {string} kernelInfo.name name of the kernel @param {string} kernelInfo.resourceDir kernel's resources directory @return {Promise<Object>} Promise for a kernelResources object
[ "Get", "a", "kernel", "resources", "object" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L22-L36
train
nteract/kernelspecs
lib/traverse.js
getKernelInfos
function getKernelInfos(directory) { return promisify(fs.readdir, [directory]).then(files => files.map(fileName => ({ name: fileName, resourceDir: path.join(directory, fileName), })) ); }
javascript
function getKernelInfos(directory) { return promisify(fs.readdir, [directory]).then(files => files.map(fileName => ({ name: fileName, resourceDir: path.join(directory, fileName), })) ); }
[ "function", "getKernelInfos", "(", "directory", ")", "{", "return", "promisify", "(", "fs", ".", "readdir", ",", "[", "directory", "]", ")", ".", "then", "(", "files", "=>", "files", ".", "map", "(", "fileName", "=>", "(", "{", "name", ":", "fileName", ",", "resourceDir", ":", "path", ".", "join", "(", "directory", ",", "fileName", ")", ",", "}", ")", ")", ")", ";", "}" ]
Gets a list of kernelInfo objects for a given directory of kernels @param {string} directory path to a directory full of kernels @return {Promise<Object[]>} Promise for an array of kernelInfo objects
[ "Gets", "a", "list", "of", "kernelInfo", "objects", "for", "a", "given", "directory", "of", "kernels" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L43-L50
train
nteract/kernelspecs
lib/traverse.js
find
function find(kernelName) { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { const kernelInfos = dirs.map(dir => ({ name: kernelName, resourceDir: path.join(dir, 'kernels', kernelName), })) return extractKernelResources(kernelInfos); }).then(kernelResource => kernelResource[kernelName]) }
javascript
function find(kernelName) { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { const kernelInfos = dirs.map(dir => ({ name: kernelName, resourceDir: path.join(dir, 'kernels', kernelName), })) return extractKernelResources(kernelInfos); }).then(kernelResource => kernelResource[kernelName]) }
[ "function", "find", "(", "kernelName", ")", "{", "return", "jp", ".", "dataDirs", "(", "{", "withSysPrefix", ":", "true", "}", ")", ".", "then", "(", "dirs", "=>", "{", "const", "kernelInfos", "=", "dirs", ".", "map", "(", "dir", "=>", "(", "{", "name", ":", "kernelName", ",", "resourceDir", ":", "path", ".", "join", "(", "dir", ",", "'kernels'", ",", "kernelName", ")", ",", "}", ")", ")", "return", "extractKernelResources", "(", "kernelInfos", ")", ";", "}", ")", ".", "then", "(", "kernelResource", "=>", "kernelResource", "[", "kernelName", "]", ")", "}" ]
find a kernel by name @param {string} kernelName the kernel to locate @return {Object} kernelResource object
[ "find", "a", "kernel", "by", "name" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L57-L67
train
nteract/kernelspecs
lib/traverse.js
findAll
function findAll() { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { return Promise.all(dirs // get kernel infos for each directory and ignore errors .map(dir => getKernelInfos(path.join(dir, 'kernels')).catch(() => {})) ).then(extractKernelResources) }); }
javascript
function findAll() { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { return Promise.all(dirs // get kernel infos for each directory and ignore errors .map(dir => getKernelInfos(path.join(dir, 'kernels')).catch(() => {})) ).then(extractKernelResources) }); }
[ "function", "findAll", "(", ")", "{", "return", "jp", ".", "dataDirs", "(", "{", "withSysPrefix", ":", "true", "}", ")", ".", "then", "(", "dirs", "=>", "{", "return", "Promise", ".", "all", "(", "dirs", "// get kernel infos for each directory and ignore errors", ".", "map", "(", "dir", "=>", "getKernelInfos", "(", "path", ".", "join", "(", "dir", ",", "'kernels'", ")", ")", ".", "catch", "(", "(", ")", "=>", "{", "}", ")", ")", ")", ".", "then", "(", "extractKernelResources", ")", "}", ")", ";", "}" ]
Get an array of kernelResources objects for the host environment This matches the Jupyter notebook API for kernelspecs exactly @return {Promise<Object<string,kernelResource>} Promise for an array of kernelResources objects
[ "Get", "an", "array", "of", "kernelResources", "objects", "for", "the", "host", "environment", "This", "matches", "the", "Jupyter", "notebook", "API", "for", "kernelspecs", "exactly" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L90-L97
train