Run-time type support for backbone models
Backbone-Typed extends the Backbone model and provides an optional Type system on top of the default models. The system is provided in run time, and is optimistic, if the value can be converted to the needed type it will, if not, it will be nulled and logged
Examples writtein in Coffee-Script but source is compiled to JS so no need to have CS installed at run time.
npm install backbone-typed
typed = require 'backbone-typed' TypedModel = typed.TypedModel Types = typed.Types
enumLike :"OPTION_1""OPTION_2""OPTION_3""OPTION_4"defaults :param1: nullparam2: nullparam3: nulltypes :param1: TypesStringparam2: TypesIntegerparam3: TypesEnumenumLikemyTypedModel = param1: "im a string"param2: "1337"param3: enumLikeOPTION_1consolelog myTypedModeltoJSON=> param1: "im a string"param2: 1337param3: "OPTION_1"# now things get interesting...myTypedModel2 = param1: 100param2: "bzzzz"param3: "NOT A REAL OPTION"consolelog myTypedModel2toJSON=> backbone-typed :: 2012-9-13 20:10:3.235 :: ERROR :: backbone-typed nulled value of:"param2" value:"bzzzz" type:"Integer"=> backbone-typed :: 2012-9-13 20:10:3.235 :: ERROR :: backbone-typed nulled value of:"param3" value:"NOT A REAL OPTION" type:"Enum"=> param1: "100"param2: nullparam3: null
Sometimes its useful to have your own method that validates input and returns some output. Backbone-typed provides a method that "signs" the passed function, so that we know its there in purpose, and will even return its name if the ".toString()" of said function is called.
# we sign the functionmyType = typedsignTypeFunction "Custom"return if param is "its me!" then "yes" else null# now use it in a modeldefaults : testMe : nulltypes : testMe : myType
More examples in specs.
Libraries of additional types