SpineJSAPI.docx
- 文档编号:9933229
- 上传时间:2023-05-22
- 格式:DOCX
- 页数:16
- 大小:19.94KB
SpineJSAPI.docx
《SpineJSAPI.docx》由会员分享,可在线阅读,更多相关《SpineJSAPI.docx(16页珍藏版)》请在冰点文库上搜索。
SpineJSAPI
Classes
SpineprovidesclassesaspartofitsJavaScriptcompatibilitylayer,asinternally,SpineusesCoffeeScriptclasses.
Classmethods
@sub([includeProperties,extendProperties])
Usedtocreatenewclasses,orinheritfromexistingones.Forexample,creatinganewclasswouldlooklikethis:
varUser=Spine.Class.sub();
Orinheritingfromanexistingclasswouldlooklikethis:
varTeacher=User.sub();
Youcanpassinanoptionalsetofincludeorextendpropertiesthatwillbeaddedtotheclass.
varUser=Spine.Class.sub({
instanceFunction:
function(){
//Blah
}
});
new
Classesareconstructorfunctions,sotheycanbeinstantiatedusingthenewkeyword:
varUser=Spine.Class.sub();
varuser=newUser;
@extend(Module)
@extend()addsclassmethods.
varUser=Spine.Class.sub();
User.extend({
find:
function(){
/*...*/
}
});
User.find();
@include(Module)
@include()addsinstancemethods.
varUser=Spine.Class.sub();
User.include({
name:
"DefaultName"
});
assertEqual((newUser).name,"DefaultName");
@proxy(function)
Wrapsafunctioninaproxy,soit'salwaysinvokedintheclass'context.
Instancemethods
proxy()
Wrapsafunctioninaproxy,soit'salwaysinvokedintheinstance'scontext.
Models
Classmethods
@configure(modelName,attributes...)
Setupthemodelanditsattributes.Thisisrequiredforeverymodel,andshouldbecalledbeforeanythingelseis.
classUserextendsSpine.Model
@configure"User","first_name","last_name"
@include(Module)
Addclassmethods;seemodules.
@extend(Module)
Addinstancemethods;seemodules
@bind(eventName,function)
Bindeventlistenerstothemodel.Theseareexecutedinthecontextofthemodel.
User.bind("refreshchange",(user)->alert("#{user.name}changed!
"))
Seeeventsformoreinformation.
@trigger(eventName,data...)
Triggeracustomevent,seeeventsformoreinformation.
@unbind([eventName,function])
Unbindevents,seetheeventsguideformoreinformation.
@records
Anhashoftherawsavedrecordinstances.Youshouldn'tneedtoaccessoralterthisdirectly.
@attributes
Anarrayofmodelattributes,setusing@configure.Youshouldn'tneedtoaccessoralterthisdirectly.
@toString()
Conveniencefunctionforrepresentingthemodel.
@find(id,[notFound])
FindrecordsbyID-returningtherecordinstance.Iftherecorddoesn'texist,@notFoundwillberununlessacustomcallbackwasalsopassedin.
user=User.find("1")
@notFound(id)
runsif@findforagiveniddoesnotfindamodelinstance.Defaultsimplyreturnsnull.Youshouldn'tneedtoinvokethisdirectly,butdefiningcustomnotFoundonaspineModelissomethingyoumaybeinterestedin.'
@exists(id)
ReturnsabooleanindicatingiftherecordwiththespecifiedIDexistsornot.
user=User.exists("1")
alert(user.name)ifuser
@refresh(recordsArray,[options])
Appendstoallthestoredrecords,withoutcallinganycreate,update,saveordestroyevents.Theonlyeventthatwillbetriggeredistherefreshevent.Youcanpasstheoption{clear:
true}towipealltheexistingrecords.Internally@refreshcallsfromJSON(),soyoucanalsopassitJSONinsteadofanarray.
User.refresh([{id:
1,name:
"test"},{id:
2,name:
"test2"}])
@select(function)
Selectallrecordsthatthecallbackfunctionreturnstrueto.
bobs=User.select(user)->user.name=="bob"
@findByAttribute(name,value)
Findthefirstrecordthathasthegivenattribute&value.
bob=User.findByAttribute("name","bob")
@findAllByAttribute(name,value)
Findallrecordsthathavethegivenattribute&value.
bobs=User.findAllByAttribute("name","bob")
@each(callback)
Iterateovereveryrecord,passingittothecallbackfunction.
User.each(user)->alert(user.name)
@all()
Returnsaclonedcopyofeveryinstance.
users=User.all()
@slice(begin[,end])
Returnsaclonedcopiesofinstancesfrombeginuptobutnotincludingend.
allUsersExceptFirst3=User.slice(3)
users7through13=User.slice(6,13)
@first([x])
Returnsaclonedcopyofthefirstrecord.oranarrayofthefirstxrecords
@last([x])
Returnsaclonedcopyofthelastrecord,oranarrayofthelastxrecords
@count()
Returnsthecountoftotalrecords.
@deleteAll()
Deleteseveryrecordwithouttriggeringanyevents.
@destroyAll(options)
Destroyseveryrecord,triggeringadestroyeventoneveryrecord.
@update(id,attributes)
UpdatestherecordwiththematchingID,withthegivenattributes.
@create(attributes)
Createsanewrecordwiththegivenattributes.Returnsfalseiftherecord'svalidationfails,orthenewlycreatedrecordifsuccessful.
@destroy(id,options)
DestroystherecordwiththegivenID.
@change([function])
Ifpassedafunction,@change()addsthatfunctionasalistenertothechangeevent.Otherwise,ittriggersthechangeevent.
@fetch([function])
Ifpassedafunction,@fetch()addsthatfunctionasalistenertothefetchevent.Otherwise,ittriggersthefetchevent.
@toJSON()
UtilityfunctionsothemodelhasavalidJSONrepresentation(showsallrecords).
@fromJSON(json)
PassaJSONstring,representingeitheranarrayorasingleton,to@fromJSON().Returnsanarrayorunsavedmodelinstances.
@fromForm(formElement)
Returnsanewrecord,populatedbythegivenHTMLform'sinputs.
@proxy(function)
Wrapafunctioninaproxysoitwillalwaysexecuteinthecontextofthemodel.ThisisaJavaScriptcompatibilityfeature,andshouldn'tbeusedinCoffeeScript.
create=Model.proxy(Model.create)
@setup(name,[attributes...])
Alternativemethodforcreatinganewmodelclass.ThisisaJavaScriptcompatibilityfeature,andshouldn'tbeusedinCoffeeScript.
varUser=Model.setup("User",["first_name","last_name"])
Instancemethods
newRecord
Booleanindicatingiftherecordhasbeensavedornot.UseisNew()instead.
isNew()
Returnsabooleanindicatingiftherecordhasbeensavedornot.
isValid()
Returnsabooleanindicatingiftherecordhaspassedvalidation.
validate()
Bydefaultanoop.Overridethistoprovidecustomvalidation.Returnastring,containingtheerrormessage,iftherecordisn'tvalid.Forexample:
classUserextendsSpine.Model
@configure"User","name"
validate:
->
"Namerequired"unless@name
load(attributes)
Loadasetofpropertiesin,settingattributes.
user=newUser
user.load(name:
"SirBob")
attributes()
Returnsahashofattributestovalues.
eql(record)
Returnsabooleanindicatingiftheotherrecordisequal(i.e.sameclassandID)asthecurrentinstance.
ifuser.eql(anotherUser)
alert("Yah!
")
save()
Createsorupdatestherecord,returningfalseiftherecord'svalidationfails,orselfiftherecordsavessuccessfully.Duringasave,thebeforeSave,changeandsaveeventsaretriggered.Alsothecreateorupdateeventswillbefireddependingonwhethertherecordwascreated/updated.
user=newUser(name:
"SirRobin")
user.save()
alert("#{user.id}wassaved")
user=User.find(user.id)
updateAttribute(name,value)
Setsasingleattribute,savingtheinstance.
user=newUser
user.updateAttribute("name","GreenKnight")
updateAttributes(attributes)
Updatesarecordwiththegivenattributes,savingtherecord.
user=User.create()
user.updateAttributes(name:
"SirGalahadthePure")
destroy()
Destroystherecord,removingitfromtherecordstoreandtriggeringthedestroyevent.
user=User.create()
user.destroy()
Destroywillalsounbindeventlistenersforthemodelandobjectsitwaslisteningto.
dup()
Returnsanewunsavedrecord,withthesameattributesasthecurrentrecord,savetheID,whichwillbenull.
user=User.create(name:
"SirBedevere")
dup=user.dup()
assertEqual(dup.name,"SirBedevere")
clone()
Returnsaprototypecloneoftherecord.ThisisusedinternallyforDynamicRecords,andisprobablynotsomethingyouneedtoworryabout.
reload()
Reloadsarecord'sattributesfromitssavedcounterpart.
toJSON()
Returnstherecord'sattributes.ThisisusedforJSONserialization:
record=newUser(name:
"SirLancelottheBrave")
assertEqual(JSON.stringify(record),'{"id":
"foo","name":
"SirLancelottheBrave"}')
$.post("/record.json",JSON.stringify(record))
toString()
Returnsastringrepresentationoftherecord.Autilityfunctionusedtodisplaytherecordintheconsole.
exists()
Returnsabooleanindicatingwhethertherecordhassaved.SimilartoisNew(),butitactuallychecksthemodelsrecordstore.
fromForm(formElement)
Populatestherecord'sattributeswithinputsfromthegivenHTMLform.
bind(name,function)
Bindtoaneventspecificallyonthisrecord.onisanavailablealias.
trigger(name,[data...])
Triggeraneventspecificallyonthisrecord.Thiswillpropagateuptothemodeltoo.
unbind([events,callback])
Unbindallevents,orjustcertainevents(asacommaseperatedlist),oraspecificcallbackforgivenevents.offisanavailablealias
proxy(function)
AJavaScriptcompatibilityfunction,thatwillwrapthegivenfunctionsothatit'salwaysexecutedinthecontextoftherecord.
Controllers
Classmethods
@extend(Module)
Addclassmethods;seemodules.
@include(Module)
Addinstancemethods;seemodules
sub()
JavaScriptcompatibilityfunctionforcreatinganewcontroller.
varUsers=Spine.Controller.sub({
init:
function(){
//...
}
});
InstanceVariables
el
@elrepresentsthecontroller'sHTMLelement,andisinstantiatedwhenthecontrollerisfirstcreated.Mostofthecontroller'soperations,suchas@html()and@append()involve@el.Youcanthinkofitastheviewthecontrollerisassociatedwith.
Youalsosetacustomelementwheninstantiatingcontrollers.
»newUsers({
el:
$(".users")
});
tag
@el'stagname.i.e.thetypeofelement@elis.
Bydefaulttagissetto"div".
»var
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- SpineJSAPI
![提示](https://static.bingdoc.com/images/bang_tan.gif)