Namespace: SC
All SproutCore methods and functions are defined inside of this namespace. You generally should not add new properties to this namespace as it may be overwritten by future versions of SproutCore.
You can also use the shorthand "SC" instead of "SproutCore".
SproutCore-runtime is a framework that provides core functions for SproutCore
including cross-platform functions, support for property observing and
objects. It's focus is on small size and performance. You can use this
in place of or along-side other cross-platform libraries such as jQuery
or
Prototype.
Defined in: core.js
Field Summary
- SC.ALIGN_BOTTOM
- SC.ALIGN_BOTTOM_LEFT
- SC.ALIGN_BOTTOM_RIGHT
- SC.ALIGN_CENTER
- SC.ALIGN_DEFAULT
- SC.ALIGN_JUSTIFY
- SC.ALIGN_LEFT
- SC.ALIGN_MIDDLE
- SC.ALIGN_RIGHT
- SC.ALIGN_TOP
- SC.ALIGN_TOP_LEFT
- SC.ALIGN_TOP_RIGHT
- SC.allowsBackspaceToPreviousPage
- SC.ANCHOR_BOTTOM
- SC.ANCHOR_BOTTOM_RIGHT
- SC.ANCHOR_CENTER
- SC.ANCHOR_LEFT
- SC.ANCHOR_RIGHT
- SC.ANCHOR_TOP
- SC.AUTO_CONTROL_SIZE
- SC.BENCHMARK_BINDING_NOTIFICATIONS
- SC.BENCHMARK_BINDING_SETUP
- SC.BEST_FIT
- SC.BEST_FIT_DOWN_ONLY
- SC.BLANK_IMAGE_DATAURL
- SC.bodyOverflowArbitrator
- SC.BOTTOM_LOCATION
- SC.BRANCH_CLOSED
- SC.BRANCH_OPEN
- SC.BROWSER
- SC.BUTTON1_STATUS
- SC.BUTTON2_STATUS
- SC.BUTTON3_STATUS
- SC.cachedVersionOf
- SC.CAPTURE_BACKSPACE_KEY
- SC.CLASS_PREFIX
- SC.COMBO_STYLES
- SC.CONTEXT_MENU_ENABLED
- SC.controllersController
- SC.CSS_PREFIX
- SC.CSS_TRANSFORM_NAMES
- SC.data
- SC.DATETIME_COMPAREDATE_TIMEZONE_ERROR
- SC.DATETIME_ISO8601
- SC.designController
- SC.Designer
- SC.DesignerDropTarget
- SC.designsController
- SC.device
- SC.DEVICE
- SC.DOM_PREFIX
- SC.DRAG_ANY
- SC.DRAG_AUTOSCROLL_ZONE_THICKNESS
- SC.DRAG_COPY
- SC.DRAG_DATA
- SC.DRAG_LINK
- SC.DRAG_MOVE
- SC.DRAG_NONE
- SC.DRAG_REORDER
- SC.DROP_AFTER
- SC.DROP_ANY
- SC.DROP_BEFORE
- SC.DROP_ON
- SC.EMPTY_PLACEHOLDER
- SC.EMPTY_STATE_NAME
- SC.ENGINE
- SC.EXIT_STATE
- SC.FILL
- SC.FILL_PROPORTIONALLY
- SC.FIXED_SIZE
- SC.FOCUS_ALL_CONTROLS
- SC.FormsEditMode
- SC.FROM_THEME
- SC.FROZEN_ERROR
- SC.FULL_HEIGHT
- SC.FULL_WIDTH
- SC.Handlebars
- SC.HOLD_BEHAVIOR
- SC.HORIZONTAL_ORIENTATION
- SC.HUGE_CONTROL_SIZE
- SC.JUMBO_CONTROL_SIZE
- SC.LARGE_CONTROL_SIZE
- SC.LAYOUT_AUTO
- SC.LAYOUT_HORIZONTAL
- SC.LAYOUT_VERTICAL
- SC.LayoutState
- SC.LEAF_NODE
- SC.LINE
- SC.LIST_ITEM_ACTION_CANCEL
- SC.LIST_ITEM_ACTION_EJECT
- SC.LIST_ITEM_ACTION_REFRESH
- SC.Locale
- SC.LOG_BINDINGS
- SC.LOG_OBSERVERS
- SC.LOGGER_LOG_DEBUG
- SC.LOGGER_LOG_DELIMITER
- SC.LOGGER_LOG_ERROR
- SC.LOGGER_LOG_GROUP_HEADER
- SC.LOGGER_LOG_GROUP_INDENTATION
- SC.LOGGER_LOG_INFO
- SC.LOGGER_LOG_WARN
- SC.LOGGER_RECORDED_LOG_TIMESTAMP_PREFIX
- SC.MIXED_STATE
- SC.MODE_APPEND
- SC.MODE_PREPEND
- SC.MODE_REPLACE
- SC.MOVES_AUTOMATIC_CHILD
- SC.MOVES_CHILD
- SC.MOVES_NEXT_CHILD
- SC.MOVES_PREVIOUS_CHILD
- SC.MULTIPLE_PLACEHOLDER
- SC.NON_PIXEL_PROPERTIES
- SC.NULL_PLACEHOLDER
- SC.ObjectCoder
- SC.OS
- SC.PageDesignController
- SC.pageFilesController
- SC.pageItemView
- SC.PARSE_COLOR_RGBRE
- SC.PICKER_FIXED
- SC.PICKER_MENU
- SC.PICKER_MENU_POINTER
- SC.PICKER_POINTER
- SC.POSITION_BOTTOM
- SC.POSITION_LEFT
- SC.POSITION_RIGHT
- SC.POSITION_TOP
- SC.PUSH_BEHAVIOR
- SC.REGULAR_CONTROL_SIZE
- SC.removeData
- SC.RESIZE_AUTOMATIC
- SC.RESIZE_MANUAL
- SC.ROOT_STATE_NAME
- SC.RootDesignerHighLightView
- SC.SCALE_NONE
- SC.SCANNER_INT_ERROR
- SC.SCANNER_OUT_OF_BOUNDS_ERROR
- SC.SCANNER_SCAN_ARRAY_ERROR
- SC.SCANNER_SKIP_ERROR
- SC.SelectionHandlesView
- SC.SelectViewMenu
- SC.SMALL_CONTROL_SIZE
- SC.SNAP_ZONE
- SC.Statechart
- SC.STRINGS
- SC.SWIPE_ANY
- SC.SWIPE_DOWN
- SC.SWIPE_HORIZONTAL
- SC.SWIPE_LEFT
- SC.SWIPE_RIGHT
- SC.SWIPE_UP
- SC.SWIPE_VERTICAL
- SC.TABBING_ONLY_INSIDE_DOCUMENT
- SC.TableDelegate
- SC.Task
- SC.TaskQueue
- SC.TestSuite
- SC.TINY_CONTROL_SIZE
- SC.TO_LEFT
- SC.TO_RIGHT
- SC.TOGGLE_BEHAVIOR
- SC.TOGGLE_OFF_BEHAVIOR
- SC.TOGGLE_ON_BEHAVIOR
- SC.TOP_LOCATION
- SC.TOP_TOOLBAR_LOCATION
- SC.UNSUPPORTED
- SC.userDefaults
- SC.VERTICAL_ORIENTATION
- SC.WELL_CONTAINER_PADDING
- SC.ZERO_POINT
- SC.ZERO_RANGE
Class Methods
- $error(description, label, code, c)
- bestStringMetricsForMaxWidth(string, maxWidth, exampleElement, classNames, ignoreEscape)
- binding(path, root)
- cacheSlotFor(your-arguments)
- centerX(innerFrame, outerFrame)
- centerY(innerFrame, outerFrame)
- cloneRange(r)
- cloneRect(r)
- convertHexToHsv(hex)
- convertHsvToHex(h, s, v)
- DateFormatter(date, f)
- download(path)
- expandColor(color)
- extend()
- getStyle(oElm, strCssRule)
- hashesForLocale(languageCode, propertyName, hashes)
- heightForString(str, width, style, classNames, ignoreEscape)
- instanceOf(scObject, scClass)
- intersectRanges(r1, r2)
- intersectRects(r1, r2)
- isPercentage(val)
- kindOf(scObject, scClass)
- mapDisplayNames(obj, level, path, seenHash, seenArray)
- maxRange(range)
- maxX(frame)
- maxY(frame)
- measureString(string, ignoreEscape)
- methodForLocale(languageCode, propertyName, method)
- metricsFor(languageCode, metrics)
- metricsForString(string, exampleElement, classNames, ignoreEscape)
- midX(frame)
- midY(frame)
- minRange(range)
- minX(frame)
- minY(frame)
- mixin(target, properties)
- normalizeURL(url)
- offset(elem, relativeToFlag)
- ok(ret)
- outlet(path, root)
- parseColor(string)
- pointInElement(point, elem, includeFlag, relativeToFlag)
- pointInRect(point, f)
- prepareStringMeasurement(exampleElement, classNames)
- propertyFromRenderDelegate(propertyName, def)
- rangesEqual(r1, r2)
- rectsEqual(r1, r2, delta)
- run(callback, target, if)
- scaleRect(rect, scale, originX, originY)
- setupBodyClassNames()
- stringFromLayout(layout)
- stringFromRect(r)
- stringsFor(lang, strings)
- subtractRanges(r1, r2)
- supplement(target, properties)
- switchScale()
- teardownStringMeasurement()
- throw(description, label, code, c)
- toColorPart(number)
- uniJapaneseConvert(str)
- unionRanges(r1, r2)
- unionRects(r1, r2)
- val(obj)
- valueInRange(value, range)
- viewFor(element)
- viewportOffset(el) Deprecated
Field Detail
SC.ALIGN_BOTTOMIf set to NO
, then pressing backspace will NOT navigate to the previous
page in the browser history, which is the default behavior in most browsers.
Usually it is best to leave this property set to NO
in order to prevent the
user from inadvertently losing data by pressing the backspace key.
Defined in: core.js.
- Default value:
- NO
- Default value:
- `{ bottom: 0 }`
- Default value:
- `{ top: 0, right: 0 }`
Layout properties to center. Note that you must also specify a width and height for this to work.
Defined in: layout.js.
- Default value:
- `{ left: 0 }`
- Default value:
- `{ right: 0 }`
- Default value:
- `{ top: 0 }`
Option for controls to automatically calculate their size (should be default on controls that use renderers).
Defined in: control.js.
Performance parameter. This will benchmark the time spent firing each binding.
Defined in: binding.js.
Performance parameter. This will benchmark the time spend configuring each binding.
Defined in: binding.js.
Stretch/shrink the shape to fit the frame while maintaining aspect ratio, such that the longest dimension will just fit within the frame
Defined in: inner_frame.js.
Shrink the shape to fit the frame while maintaining aspect ratio, such that the longest dimension will just fit within the frame. Do not stretch the shape if the shape's width is less than the frame's width.
Defined in: inner_frame.js.
SC.bodyOverflowArbitrator
is a central object responsible for controlling the overflow on the body element.
Use it from views that would otherwise set the body overflow style directly; call requestHidden
to ask for
the body to have overflow:hidden, and call requestVisible
to ask for the body to be visible.
Call withdrawRequest
to register that you no longer have any interest in the body overflow setting. Don't
forget to do this, or your object could be affecting the body overflow long after it's no longer relevant.
When calling requestHidden
, requestVisible
, and withdrawRequest
, pass your object as the first argument so
that its request can be associated with its GUID.
When calling requestHidden
or requestVisible
, you may optionally pass true as a second argument to signify
that your desire for hidden or visible overflow is important. An important visible-request will override
any other, but an important hidden-request will override a normal visible-request. A normal visible-request
will in turn override a normal hidden-request.
Defined in: body_overflow.js.
Defined in: collection_content.js.
Defined in: collection_content.js.
- Default value:
- 'button1'
- Default value:
- 'button2'
- Default value:
- 'button3'
Returns a wrapped copy of your function that caches its results according to its arguments. This function itself is cached, so the function you receive when you pass in a particular function will always be the same function.
How was does this function handle its own caching? Using itself, of course! :-D
Use this only on functions without side effects you depend on, and only on functions whose outputs depend entirely on their arguments and on nothing else external to them that could change.
Defined in: string_metric_optimization.js.
Defined in: root_responder.js.
The list of browser specific object prefixes, these are matched to the browser engine.
Defined in: browser.js.
Defined in: render_context.js.
Defined in: controllers.js.
The list of browser specific CSS prefixes, these are matched to the browser engine.
Defined in: browser.js.
Reads or writes data from a global cache. You can use this facility to store information about an object without actually adding properties to the object itself. This is needed especially when working with DOM, which can leak easily in IE.
To read data, simply pass in the reference element (used as a key) and the name of the value to read. To write, also include the data.
You can also just pass an object to retrieve the entire cache.
Defined in: core.js.
Standard error thrown when trying to compare two dates in different timezones.
Defined in: datetime.js.
- Default value:
- '%Y-%m-%dT%H:%M:%S%Z'
Defined in: designer_drop_target.js.
(Document Your Controller Here)
this controller is used by Greenhouse to list all of the views in a page files
Defined in: designs.js.
The device object allows you to check device specific properties such as orientation and if the device is offline, as well as observe when they change state.
Orientation
When a touch device changes orientation, the orientation property will be set accordingly which you can observe
Offline support
In order to build a good offline-capable web application, you need to know when your app has gone offline so you can for instance queue your server requests for a later time or provide a specific UI/message.
Similarly, you also need to know when your application has returned to an 'online' state again, so that you can re-synchronize with the server or do anything else that might be needed.
By observing the 'isOffline' property you can be notified when this state changes. Note that this property is only connected to the navigator.onLine property, which is available on most modern browsers.
Defined in: device.js.
The list of browser specific DOM prefixes, these are matched to the browser engine.
Defined in: browser.js.
Special drag operation passed to delegate if the collection view proposes to perform a reorder event.
Defined in: collection.js.
Indicates that the collection view expects to accept a drop AFTER the
specified item. This is treated just like SC.DROP_BEFORE
is most views
except for tree lists.
Defined in: core.js.
Indicates that the collection view want's to know which operations would be allowed for either drop operation.
Defined in: core.js.
Indicates that the collection view expects to accept a drop BEFORE the specified item.
Defined in: core.js.
Indicates that the collection view expects to accept a drop ON the specified item.
Defined in: core.js.
Stretch/shrink the shape to fill the frame while maintaining aspect ratio, such that the shortest dimension will just fit within the frame and the longest dimension will overflow and be cropped.
Defined in: inner_frame.js.
Prevents the view from getting resized when the SplitView is resized, or the user resizes or moves an adjacent child view.
Defined in: split.js.
If true, then all SproutCore controls can be focused when the user presses the
tab key. Otherwise, only SC.TextFieldView
's will be focused.
Defined in: core.js.
- Default value:
- false
Defined in: view.js.
Defined in: freezable.js.
Prepares the Handlebars templating library for use inside SproutCore's view system.
The SC.Handlebars
object is the standard Handlebars library, extended to use
SproutCore's get() method instead of direct property access, which allows
computed properties to be used inside templates.
To use SC.Handlebars
, call SC.Handlebars.compile().
This will return a
function that you can call multiple times, with a context object as the first
parameter:
var template = SC.Handlebars.compile("my {{cool}} template");
var result = template({
cool: "awesome"
});
console.log(result); // prints "my awesome template"
Note that you won't usually need to use SC.Handlebars
yourself. Instead, use
SC.TemplateView
, which takes care of integration into the view layer for you.
Defined in: handlebars.js.
States that the view's layout can be set to if its animation is cancelled.
START
The previous layout of the view before calling animate.
For example,
myView.set('layout', { left: 0, top: 0, width: 100, bottom: 0 });
myView.animate('left', 300, { duration: 1.5 });
// later..
myView.cancelAnimation(SC.LayoutState.START);
myView.get('layout'); // => { left: 0, top: 0, width: 100, bottom: 0 }
CURRENT
The current layout of the view while it is animating.
For example,
myView.set('layout', { left: 0, top: 0, width: 100, bottom: 0 });
myView.animate('left', 300, { duration: 1.5 });
// later..
myView.cancelAnimation(SC.LayoutState.CURRENT);
myView.get('layout'); // => { left: 150, top: 0, width: 100, bottom: 0 }
END
The final layout of the view if the animation completed.
For example,
myView.set('layout', { left: 0, top: 0, width: 100, bottom: 0 });
myView.animate('left', 300, { duration: 1.5 });
// later..
myView.cancelAnimation(SC.LayoutState.END);
myView.get('layout'); // => { left: 300, top: 0, width: 100, bottom: 0 }
Defined in: animation.js.
This View is used by Greenhouse when application is in design mode This is a Drawing View: If you want to draw a new shape you can pass in the information: For a Line:
{
+shape: SC.LINE,
+start: {x: 0, y: 0},
+end: {x: 100, y: 100},
?style: {
?width: 5,
?color: 'orange' | '#FFA500' | 'rgb(255,165,0)' | 'rgba(255,165,0,1)'
?transparency: 0.2
}
}
For a Rectangle:
{
+shape: SC.RECT,
+start: {x: 0, y: 0},
+size: {width: 100, height: 100},
?type: SC.FILL | SC.STROKE
?style: {
?width: 5,
?color: 'orange' | '#FFA500' | 'rgb(255,165,0)' | 'rgba(255,165,0,1)'
?transparency: 0.2
}
}
For a Circle:
{
+shape: SC.CIRCLE,
+center: {x: 0, y: 0},
+radius: 20,
?type: SC.FILL | SC.STROKE
?style: {
?width: 5,
?color: 'orange' | '#FFA500' | 'rgb(255,165,0)' | 'rgba(255,165,0,1)'
?transparency: 0.2
}
}
For a Polygon:
{
+shape: SC.POLY
+path: [
+{x: 0, y: 0},
+{x: 10, y: 10},
?{x: 0, y: 50}
],
?type: SC.FILL | SC.STROKE
?style: {
?width: 5,
?color: 'orange' | '#FFA500' | 'rgb(255,165,0)' | 'rgba(255,165,0,1)'
?transparency: 0.2
}
}
Defined in: drawing.js.
Author: Evin Grano.
- Since:
- SproutCore 1.0
The Locale defined information about a specific locale, including date and
number formatting conventions, and localization strings. You can define
various locales by adding them to the SC.locales
hash, keyed by language
and/or country code.
On page load, the default locale will be chosen based on the current
languages and saved at SC.Locale.current.
This locale is used for
localization, etc.
Creating a new locale
You can create a locale by simply extending the SC.Locale
class and adding
it to the locales hash:
SC.Locale.locales['en'] = SC.Locale.extend({ .. config .. }) ;
Alternatively, you could choose to base your locale on another locale by extending that locale:
SC.Locale.locales['en-US'] = SC.Locale.locales['en'].extend({ ... }) ;
Note that if you do not define your own strings property, then your locale will inherit any strings added to the parent locale. Otherwise you must implement your own strings instead.
Defined in: locale.js.
- Since:
- SproutCore 1.0
Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily.
Defined in: binding.js.
Set to YES
to have all observing activity logged to the console.
This is only available in debug mode.
Defined in: observable.js.
If {@link SC.Logger.debug
} falls back onto {@link SC.Logger.log
}, this will be
prepended to the output.
Defined in: logger.js.
If {@link SC.Logger.error
} falls back onto {@link SC.Logger.log
}, this will be
prepended to the output.
Defined in: logger.js.
If {@link SC.Logger.group
} falls back onto {@link SC.Logger.log
}, this will
be prepended to the output.
Defined in: logger.js.
If the reporter does not support group(), then we’ll add our own indentation to our output. This constant represents one level of indentation.
Defined in: logger.js.
If {@link SC.Logger.info
} falls back onto {@link SC.Logger.log
}, this will be
prepended to the output.
Defined in: logger.js.
If {@link SC.Logger.warn
} falls back onto {@link SC.Logger.log
}, this will be
prepended to the output.
Defined in: logger.js.
When reporting recorded log messages, the timestamp is included with this prefix.
Defined in: logger.js.
Tells the SplitThumb to automatically choose which child of the SplitView
to move in response to touch or mouse events in an SC.SplitThumb.
Defined in: split_thumb.js.
Tells the SplitThumb to move the child of the SplitView that is either the SplitThumb or a parent of it.
Defined in: split_thumb.js.
Tells the SplitThumb to move the child of the SplitVie that comes after the child that is either the SplitThumb or a parent of it.
Defined in: split_thumb.js.
Tells the SplitThumb to move the child of the SplitView that preceeds the child that is either the SplitThumb or a parent of it.
Defined in: split_thumb.js.
Generic base class to encode a view hierarchy. ViewCoder
s are used to
collect the properties that may be included in a view design and then to
serialize that design to a JavaScript string that can be evaled.
To encode a view with a ViewCoder
, simply call SC.ViewCoder.encode(view)
.
Most of the time, however, you will not initiate coding directly but instead
work with the coder while designing an SC.DesignerView
subclass.
Using a Coder
When you are passed an instance of a coder, you can simply write attributes into the coder using one of the many encoding methods defined on the view. Encoding methods are defined for most primitive view types.
coder.string("firstName" , "Charles").string('lastName', 'Jolley');
Defined in: object.js.
An instance of this controller is created for every page where designers are involved. The Designer's themselves will register with the controller so that you can hook to the controller to manage the views and their editors.
Among other things, this controller implements global selection support for the designers.
Defined in: page_design.js.
- Since:
- SproutCore 1.0
Defined in: page_files.js.
This View is used by Greenhouse when application is in design mode Used for displaying page items
Defined in: page_item_view.js.
Author: Mike Ball.
Removes data from the global cache. This is used throughout the framework to hold data without creating memory leaks.
You can remove either a single item on the cache or all of the cached data for an object.
Defined in: core.js.
Allows the view to be resized when the SplitView is resized or due to the user resizing or moving an adjacent child view.
Defined in: split.js.
Prevents the view from getting resized when the SplitView is resized (unless the SplitView has resized all other views), but allows it to be resized when the user resizes or moves an adjacent child view.
Defined in: split.js.
This View is used by Greenhouse when application is in design mode
It darkens the area around the rootDesigner
Defined in: high_light.js.
Defined in: datetime.js.
Standard error thrown by SC.Scanner
when it can any kind a string in the
matching array.
Defined in: datetime.js.
Defined in: datetime.js.
This View is used by Greenhouse when application is in design mode This view draws selection handles for a given designer. It will also forward any mouse events to the underlying designer.
Defined in: selection_handles.js.
Defined in: select_view_menu.js.
Defined in: snap_lines.js.
Author:
Mike Ball
Add this Mixin to any View and it gives you an API to draw snap lines for all the child views
.Default property to disable or enable if the focus can jump to the address bar or not.
Defined in: view.js.
Represents a single task which can be run by a task queue. Note that tasks are actually allowed to add themselves back onto the queue if they did not/ might not finish.
Defined in: task.js.
Runs a set of tasks. Most importantly, has a runWhenIdle
option that allows
it to run when no user input is occurring. This allows, for instance, preloading
bundles while not blocking user interaction.
Defined in: task_queue.js.
Adds a new module of unit tests to verify that the passed object implements
the SC.Array
interface. To generate, call the ArrayTests array with a
test descriptor. Any properties you pass will be applied to the ArrayTests
descendant created by the create method.
You should pass at least a newObject
() method, which should return a new
instance of the object you want to have tested. You can also implement the
destroyObject
() method, which should destroy a passed object.
SC.ArrayTests.generate("Array", {
newObject: function() { return []; }
});
newObject
must accept an optional array indicating the number of items
that should be in the array. You should initialize the the item with
that many items. The actual objects you add are up to you.
Unit tests themselves can be added by calling the define() method. The function you pass will be invoked whenever the ArrayTests are generated. The parameter passed will be the instance of ArrayTests you should work with.
SC.ArrayTests.define(function(T) {
T.module("length");
test("verify length", function() {
var ary = T.newObject();
equals(ary.get('length'), 0, 'should have 0 initial length');
});
}
Defined in: base.js.
- Default value:
- 15
Class Method Detail
Defined in: error.js.
- Parameters:
- description
- {String} human readable description of the error
- label
- {String} human readable name of the item with the error
- code
- {Number} an error code to use for testing.
- c
- Returns:
- SC.Error
- new error instance.
This function is similar to SC.metricsForString
, but takes an extra argument after the string and before the exampleElement
.
That extra argument is maxWidth, which is the maximum allowable width in which the string can be displayed. This function
will find the narrowest width (within maxWidth) that keeps the text at the same number of lines it would've normally wrapped
to had it simply been put in a container of width maxWidth.
If you have text that's 900 pixels wide on a single line, but pass maxWidth as 800, the metrics that will be returned will specify a height of two lines' worth of text, but a width of only around 450 pixels. The width this function determines will cause the text to be split as evenly as possible over both lines.
If your text is 1500 pixels wide and maxWidth is 800, the width you'll get back will be approximately 750 pixels, because the 1500 horizontal pixels of text will still fit within two lines.
If your text grows beyond 1600 horizontal pixels, it'll wrap to three lines. Suppose you have 1700 pixels of text. This much text would require three lines at 800px per line, but this function will return you a width of approximately 1700/3 pixels, in order to fill out the third line of text so it isn't just ~100px long.
A binary search is used to find the optimimum width. There's no way to ask the browser this question, so the answer must be searched for. Understandably, this can cause a lot of measurements, which are NOT cheap.
Therefore, very aggressive caching is used in order to get out of having to perform the search. The final optimimum width is a result of all the following values:
- The string itself
- The styles on the
exampleElement
- The
classNames
passed in - Whether
ignoreEscape
isYES
or NO
The caching goes against all of these in order to remember results. Note that maxWidth
, though an argument, isn't one of them;
this means that the optimal width will be searched for only once per distinct number of lines of text for a given string and
styling. However, due to the fact that a passed exampleElement
can have different styles a subsequent time it's passed in (but
still remains the same object with the same GUID, etc), caching will not be enabled unless you either pass in a style string
instead of an element, or unless your element has cacheableForMetrics: YES as a key on it. In most situations, the styles on
an element won't change from call to call, so this is purely defensive and for arguably infrequent benefit, but it's good
insurance. If you set the cacheableForMetrics key to YES
on your exampleElement
, caching will kick in, and repeated calls to
this function will cease to have any appreciable amortized cost.
The caching works by detecting and constructing known intervals of width for each number of lines required by widths in those
intervals. As soon as you get a result from this function, it remembers that any width between the width it returned and the
maxWidth
you gave it will return that same result. This also applies to maxWidths
greater than the with you passed in, up
until the width at which the text can fit inside maxWidth
with one fewer line break. However, at this point, the function
can't know how MUCH larger maxWidth
can get before getting to the next widest setting. A simple check can be done at this point
to determine if the existing cached result can be used: if the height of the string at the new maxWidth
is the same as the
cached height, then we know the string didn't fit onto one fewer line, so return the cached value. If we did this check, we
could return very quickly after only one string measurement, but EACH time we increase the maxWidth
we'll have to do a new
string measurement to check that we didn't end up with horizontal room for one fewer line. Because of this, instead of doing
the check, the function will perform its binary search to go all the way UP to the minimum maxWidth
at which one fewer line
can be used to fit the text. After caching this value, all subsequent calls to the function will result in no string
measurements as long as all the maxWidths
are within the interval determined to lead to the cached result. So, the second call
can in some cases be more expensive than it needs to be, but this saves A LOT of expense on all subsequent calls. The less
often one calls metricsForString
, the happier one's life is.
The amount of time this function will take ranges from 0 to maybe 35ms on an old, slow machine, and, when used for window resizing, you'll see 35, 20, 0, 0, 0, ..., 0, 0, 35, 0, 0, 0, ..., 0, 0, 35, 0, 0, 0, ..., 0, 0, 0, 35, 0, 0, 0, ... After resizing through all the different caching intervals, the function will always execute quickly... under 1ms nearly always. The expensive calls are when a caching interval is crossed and a new cached set of metrics for the new number of lines of text must be calculated. And in reality, the number of sub-millisecond function calls will be much greater relative to the number of expensive calls, because window resizing just works like that.
Defined in: string_metric_optimization.js.
- Parameters:
- string String
- The text whose width you wish to optimize within your maximum width preference.
- maxWidth Number
- The maximum width the text is allowed to span, period. Can have "px" afterwards. Need not be a whole number. It will be stripped of "px", and/or rounded up to the nearest integer, if necessary.
- exampleElement Element/String
- The element whose styles will be used to measure the width and height of the string. You can pass a string of CSSText here if you wish, just as with SC.metricsForString.
- classNames String Optional
- Optional. Any class names you wish to also put on the measurement element.
- ignoreEscape Boolean Optional
- Optional. If true, HTML in your string will not be escaped. If false or omitted, any HTML characters will be escaped for the measurement. If it's omitted where it should be true for correct results, the metrics returned will usually be much bigger than otherwise required.
Shorthand method to define a binding. This is the same as calling:
SC.binding(path)
= SC.Binding.from(path)
Defined in: binding.js.
- Parameters:
- path
- root
Supply any number of arguments of any type, and this function will return you a hash associated with all those arguments. Call it twice with the same arguments in the same order, and the hash is the same. This is great for getting out of calculations whose answers depend on many different variables.
Defined in: string_metric_optimization.js.
- Parameters:
- your-arguments anything
- Any set of arguments whatsoever. If the FIRST argument is an array (including Arguments arrays), all other arguments will be ignored and the array will be treated as if its values at its numerical indices were passed in themselves as individual arguments.
- Returns:
- Hash
- A cached workspace mapped to the ordered *n*-tuple of arguments passed into it.
Defined in: utils.js.
- Parameters:
- innerFrame
- outerFrame
Defined in: utils.js.
- Parameters:
- innerFrame
- outerFrame
Defined in: range.js.
- Parameters:
- r
- Parameters:
- r
- {Rect} The rect to clone.
- Returns:
- Rect
- The cloned rect
Defined in: colors.js.
- Parameters:
- hex
Defined in: colors.js.
- Parameters:
- h
- s
- v
SC.DateFormatter
is used with String.fmt
to format dates with a format
string. For example:
"My date: %{date:yyyy} %{date:MM} %{date:dd}".fmt(myDate, SC.DateFormatter)
You can use almost any of the Unicode Technical Standard #35 (draft 10) formatting strings. See:
http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns
Note that you can only put one (yyyy, MM, dd) per token, but you can put as many tokens as you'd like.
Defined in: date_formatter.js.
- Parameters:
- date
- f
Starts a download of the file at the named path.
Use this method when you want to cause a file to be downloaded to a users desktop instead of having it display in the web browser. Note that your server must return a header indicating that the file is intended for download also.
Defined in: misc.js.
- Parameters:
- path
Defined in: colors.js.
- Parameters:
- color
Defined in: misc.js.
- Parameters:
- oElm
- strCssRule
This special helper will store the propertyName
/ hashes pair you pass
in the locale matching the language code. If a locale is not defined
from the language code you specify, then one will be created for you
with the english locale as the parent.
Defined in: locale.js.
Given a string and a fixed width, calculates the height of that block of text using a style string, a set of class names, or both.
Defined in: string_measurement.js.
- Parameters:
- str
- {String} The text to calculate
- width
- {Number} The fixed width to assume the text will fill
- style
- {String} A CSS style declaration. E.g., 'font-weight: bold'
- classNames
- {Array} An array of class names that may affect the style
- ignoreEscape
- {Boolean} To NOT html escape the string.
- Returns:
- Number
- The height of the text given the passed parameters
Same as the instance method, but lets you check instanceOf
without
having to first check if instanceOf
exists as a method.
Defined in: object.js.
Defined in: range.js.
- Parameters:
- r1
- r2
Defined in: rect.js.
- Parameters:
- r1
- {Rect} The first rect
- r2
- {Rect} the second rect
- Returns:
- Rect
- the intersection rect. width || height will be 0 if they do not interset.
Defined in: utils.js.
- Parameters:
- val
Same as the instance method, but lets you check kindOf
without having to
first check if kindOf
exists as a method.
Defined in: object.js.
Defined in: core.js.
- Parameters:
- obj
- level
- path
- seenHash
- seenArray
Defined in: range.js.
- Parameters:
- range
Defined in: utils.js.
- Parameters:
- frame
Defined in: utils.js.
- Parameters:
- frame
Measures a string in the prepared environment.
An easier and simpler alternative (but less efficient for bulk measuring) is metricsForString
.
Defined in: string_measurement.js.
- Parameters:
- string
- {String} The string to measure.
- ignoreEscape
- {Boolean} To NOT html escape the string.
Defined in: locale.js.
Defined in: locale.js.
Given a string and an example element or style string, and an optional set of class names, calculates the width and height of that block of text.
To constrain the width, set max-width on the exampleElement
or in the style string.
Defined in: string_measurement.js.
- Parameters:
- string
- {String} The string to measure.
- exampleElement
- The example element to grab styles from, or the style string to use.
- classNames
- {String} (Optional) Class names to add to the test element.
- ignoreEscape
- {Boolean} To NOT html escape the string.
Defined in: utils.js.
- Parameters:
- frame
Defined in: utils.js.
- Parameters:
- frame
Defined in: range.js.
- Parameters:
- range
Defined in: utils.js.
- Parameters:
- frame
Defined in: utils.js.
- Parameters:
- frame
Adds properties to a target object.
Takes the root object and adds the attributes for any additional arguments passed.
Takes a URL of any type and normalizes it into a fully qualified URL with hostname. For example:
"some/path" => "http://localhost:4020/some/path"
"/some/path" => "http://localhost:4020/some/path"
"http://localhost:4020/some/path" => "http://localhost:4020/some/path"
Defined in: utils.js.
- Parameters:
- url
- {String} the URL
- Returns:
- String
- the normalized URL
The offset of an element.
This function returns the left and top offset of an element with respect to either the document, the viewport or the element's parent element. In standard SproutCore applications, the coordinates of the viewport are equivalent to the document, but a HTML5 application that wishes to use this component of SproutCore might need to properly distinguish between the two.
For a useful discussion on the concepts of offsets and coordinates, see: http://www.quirksmode.org/mobile/viewports.html.
Defined in: utils.js.
- Parameters:
- elem DOMElement|jQuery|String
- the element to find the offset of. This is passed to `jQuery()`, so any value supported by `jQuery()` will work.
- relativeToFlag String
- flag to determine which relative element to determine offset by. One of either: 'document', 'viewport' or 'parent' (default: 'document').
- Returns:
- Object
- the offset of the element as an Object (ie. Hash) in the form { x: value, y: value }.
Defined in: error.js.
Generates a computed property that will look up the passed property path the first time you try to get the value. Use this whenever you want to define an outlet that points to another view or object. The root object used for the path will be the receiver.
Defined in: view.js.
- Parameters:
- path
- root
Defined in: colors.js.
- Parameters:
- string
Determines if the given point is within the given element.
The test rect will include the element's padding and can be configured to optionally include the border or border and margin.
Defined in: misc.js.
- Parameters:
- point Object
- the point as an Object (ie. Hash) in the form { x: value, y: value }.
- elem DOMElement|jQuery|String
- the element to test inclusion within. This is passed to `jQuery()`, so any value supported by `jQuery()` will work.
- includeFlag String
- flag to determine the dimensions of the element to test within. One of either: 'padding', 'border' or 'margin' (default: 'border').
- relativeToFlag String
- flag to determine which relative element to determine offset by. One of either: 'document', 'viewport' or 'parent' (default: 'document').
- Returns:
- Boolean
- YES if the point is within the element; NO otherwise
Defined in: rect.js.
- Parameters:
- point
- f
Sets up a string measuring environment.
You may want to use this, in conjunction with teardownStringMeasurement
and
measureString
, instead of metricsForString
, if you will be measuring many
strings with the same settings. It would be a lot more efficient, as it
would only prepare and teardown once instead of several times.
Defined in: string_measurement.js.
- Parameters:
- exampleElement
- The example element to grab styles from, or the style string to use.
- classNames
- {String} (Optional) Class names to add to the test element.
Generates a computed property that will look up the specified property from the view's render delegate, if present. You may specify a default value to return if there is no such property or is no render delegate.
The generated property is read+write, so it may be overridden.
Defined in: theming.js.
- Parameters:
- propertyName String
- The name of the property to get from the render delegate..
- def Value
- The default value to use if the property is not present.
Returns true if the two passed ranges are equal. A null value is
treated like RANGE_NOT_FOUND.
Defined in: range.js.
- Parameters:
- r1
- r2
Defined in: rect.js.
- Parameters:
- r1
- {Rect} the first rect
- r2
- {Rect} the second rect
- delta
- {Float} an optional delta that allows for rects that do not match exactly. Defaults to 0.1
- Returns:
- Boolean
- true if rects match
Executes a passed function in the context of a run loop. If called outside a runloop, starts and ends one. If called inside an existing runloop, is simply executes the function unless you force it to create a nested runloop.
If an exception is thrown during execution, we give an error catcher the opportunity to handle it before allowing the exception to bubble again.
Defined in: run_loop.js.
Defined in: rect.js.
- Parameters:
- rect Rect
- The rectangle to scale.
- scale Number|Array|Hash
- The scale (or [scaleX, scaleY], or { x: scaleX, y: scaleY}) to apply. Defaults to 1.
- originX Number
- The horizontal scale origin. Defaults to 0.5 (center).
- originY Number
- The vertical scale origin. Defaults to 0.5 (center).
- Returns:
- Rect
- The scaled rect.
Defined in: loader.js.
Returns a string representation of the layout hash.
Layouts can contain the following keys:
- left: the left edge
- top: the top edge
- right: the right edge
- bottom: the bottom edge
- height: the height
- width: the width
- centerX: an offset from center X
- centerY: an offset from center Y
- minWidth
: a minimum width
- minHeight
: a minimum height
- maxWidth
: a maximum width
- maxHeight
: a maximum height
- rotateX
- rotateY
- rotateZ
- scale
Defined in: string_measurement.js.
- Parameters:
- layout
- {Hash} The layout hash to stringify.
- Returns:
- String
- A string representation of the layout hash.
Defined in: rect.js.
- Parameters:
- r
- {Rect} The rect to stringify.
- Returns:
- String
- A string representation of the rect.
This is a simplified handler for installing a bunch of strings. This ignores the language name and simply applies the passed strings hash.
Defined in: core.js.
Defined in: range.js.
- Parameters:
- r1
- r2
Adds properties to a target object. Unlike SC.mixin
, however, if the target
already has a value for a property, it will not be overwritten.
Takes the root object and adds the attributes for any additional arguments passed.
Switch the scale of your app. Useful when visualizing apps not designed for iphone.
Defined in: misc.js.
Tears down the string measurement environment. Usually, this doesn't have to be called, but there are too many what ifs: for example, what if the measurement environment has a bright green background and is over 10,000px wide? Guess what: it will become visible on the screen.
So, generally, we tear the measurement environment down so that it doesn't cause issue. However, we keep the DOM element for efficiency.
Defined in: string_measurement.js.
Defined in: error.js.
- Parameters:
- description
- {String} human readable description of the error
- label
- {String} human readable name of the item with the error
- code
- {Number} an error code to use for testing.
- c
- Returns:
- SC.Error
- new error instance.
Defined in: colors.js.
- Parameters:
- number
Defined in: misc.js.
- Parameters:
- str
Returns the union of two ranges. If one range is null, the other range will be returned.
Defined in: range.js.
- Parameters:
- r1
- r2
Defined in: rect.js.
- Parameters:
- r1
- {Rect} The first rect
- r2
- {Rect} The second rect
- Returns:
- Rect
- The union rect.
Returns the value of an object. If the passed object is an error, returns the value associated with the error; otherwise returns the receiver itself.
Defined in: error.js.
Defined in: range.js.
- Parameters:
- value
- range
Returns the SC.View
instance managing the given element.
If no instance is found, returns null
.
Defined in: core.js.
- Parameters:
- element DOMElement
- The element to check.
- Returns:
- SC.View
- The view managing the element or null if none found.
Use SC.offset
instead.
SC.offset()
is more accurate, more flexible in the value for the element parameter and
easier to understand.
Defined in: utils.js.
- Parameters:
- el
- The DOM element
- Returns:
- Point
- A hash with x, y offsets.