jquery.model.list-api
2013-06-10 17:42
204 查看
jQuery.Model.Listclass
plugin:jquery/model/listdownload:
jQuery.Model.List
test:
Model.Listsmanagealists(orarrays)ofmodelinstances.Similarto
$.Model,theyareusedto:
createeventswhenalistchanges
makeAjaxrequestsonmultipleinstances
addhelperfunctionformultipleinstances(ACLs)
The
CreatingAListClass
Createa`$.Model.Listclassfora$.Modellike:
$.Model('Todo'
)
$.Model.List('Todo.List'
,{
//staticproperties
},{
//prototypeproperties
})
Thiscreatesa
Todo.Listclassforthe
Todoclass.Thiscreatessomeniftymagicthatwewillseesoon.
staticpropertiesaretypicallyusedtodescribehowalistmakesrequests.
prototypepropertiesarehelperfunctionsthatoperateonaninstanceofalist.
MakeaHelperFunction
Often,auserwantstoselectmultipleitemsonapageandperformsomeactiononthem(forexample,deletingthem).Theappneedstoindicateifthisispossible(forexample,byenablinga"DELETE"button).Ifwegettododatabacklike:
//GET/todos.json->[code]
[{
"id"
:1
,
"name"
:"dishes"
,
"acl"
:"rwd"
},{
"id"
:2
,
"name"
:"laundry"
,
"acl"
:"r"
},...]
Wecanaddahelperfunctiontoletusknowifwecandeletealltheinstances:
$.Model.List('Todo.List'
,{
},{
canDelete:function(){
returnthis
.grep(function(todo){
return
todo.acl.indexOf("d"
)!=0
}).length==this
.length
}
})
canDeletegetsalistofalltodosthathavedintheiracl.Ifalltodoshave
d,then
canDeletereturnstrue.
GetaListInstance
YoucancreateamodellistinstancebyusingnewTodo.List(instances)like:
var[code]todos=new
Todo.List([
new
Todo({id:1
,name:...}),
new
Todo({id:2
,name:...}),
]);
Andcall
canDeleteonitlike:
todos.canDelete()//->boolean
BUT!$.Model,
$.fn.models,and$.Model.Listaredesignedtoworkwitheachother.
Whenyouuse
Todo.findAll,itwillcallbackwithaninstanceof
Todo.List:
Todo.findAll({},function(todos){
todos.canDelete()//->boolean
})
Ifyouareaddingthemodelinstancetoelementsandretrievingthembackwith
$().models(),itwillreturnainstanceof
Todo.List.Thefollowingreturnsifthechecked
.todoelementsaredeletable:
//getthecheckedinputs[code]
$('.todoinput:checked'
)
//getthetodoelements
.closest('.todo'
)
//getthemodellist
.models()
//checkcanDelete
.canDelete()
MakeAjaxRequestswithLists
Aftercheckingifwecandeletethetodos,weshoulddeletethemfromtheserver.Like$.Model,wecanaddastatic
destroyurl:
$.Model.List('Todo.List'
,{
destroy:'POST/todos/delete'
},{
canDelete:function(){
returnthis
.grep(function(todo){
return
todo.acl.indexOf("d"
)!=0
}).length==this
.length
}
})
andcall
destroyonourlist.
//getthecheckedinputs[code]
var[code]todos=$('.todoinput:checked'
)
//getthetodoelements
.closest('.todo'
)
//getthemodellist
.models()
if[code](todos.canDelete()){
todos.destroy()
}
Bydefault,destroywillcreateanAJAXrequesttodeletetheseinstancesontheserver,whentheAJAXrequestissuccessful,theinstancesareremovedfromthelistandeventsaredispatched.
ListeningtoeventsonLists
Usebind
(eventName,handler(event,data))tolistentoadd,
remove,andupdatedeventsonalist.
Whenamodelinstanceisdestroyed,itisremovedfromalllists.Inthetodoexample,wecanbindtoremovetoknowwhenatodohasbeendestroyed.Thefollowingremovesallthetodoelementsfromthepagewhentheyareremovedfromthelist:
todos.bind('remove'
,function(ev,removedTodos){
removedTodos.elements().remove();
})
Demo
Thefollowingdemoillustratesthepreviousfeatureswithacontactslist.CheckmultipleContactsandclick"DESTROYALL"Demo
HTML
Source
OtherListFeatures
StoreandretrievemultipleinstancesFastHTMLinserts
Storeandretrievemultipleinstances
Onceyouhaveacollectionofmodels,youoftenwanttoretrieveandupdatethatlistwithnewinstances.Storingandretrievingisapowerfulfeatureyoucanleveragetomanageandmaintainalistofmodels.Tostoreanewmodelinstanceinalist...
listInstance.push(new
Animal({type:dog,id:123
}))
Tolaterretrievethatinstanceinyourlist...
var[code]animal=listInstance.get(123
);
FasterInserts
The'easy'waytoaddamodeltoanelementissimplyinsertingthemodelintotheviewlike:<div<%=task%>[code]>Atask</div>[/code]
Andthenyoucanuse
$('.task').models().
Thispatternisfastenoughfor90%ofallwidgets.Butitdoesrequireanextraquery.Listshelpyouavoidthis.
The
getmethodtakeselementsandusestheirclassNametoreturnmatchedinstancesinthelist.
Touseget,yourelementsneedtohavetheinstance'sidentityintheirclassName.Sotosetupadivtoreprsentatask,youwouldhavethefollowinginaview:
<divclass='task<%=task.identity()%>'>[code]Atask</div>[/code]
Then,withyourmodellist,youcouldusegettogetalistoftasks:
taskList.get($('.task'
))
Thefollowingdemonstrateshowtousethistechnique:
Demo
HTML
<divid="contacts"></div>[code]
<divid="update"></div>
Source
steal('jquery/model'
,
'jquery/dom/fixture'
,
'jquery/model/list'
,
function(){
//===============SETUPFIXTURES===============[code]
$.fixture("GET/recipes.json"
,function(){
return
[[{'id'
:1
,'name'
:'JustinMeyer'
,'birthday'
:'1982-10-20'
},
{'id'
:2
,'name'
:'BrianMoschel'
,'birthday'
:'1983-11-10'
},
{'id'
:3
,'name'
:'AlexGomes'
,'birthday'
:'1980-2-10'
}]];
});
$.fixture("PUT/recipes/{id}.json"
,function(){
return
{};
})
//===============ContactModel===============[code]
$.Model("Contact"
,{
attributes:{
birthday:'date'
},
convert:{
//aconvertertohandledateslike12-12-2012
date:function(raw){
if
(typeof
raw=='string'
){
var
matches=raw.match(/(\d+)-(\d+)-(\d+)/
)
returnnew
Date(+matches[1
],
(+matches[2
])-1
,
+matches[3
])
}elseif
(rawinstanceof
Date){
return
raw;
}
}
},
findAll:"/recipes.json"
,
update:"/recipes/{id}.json"
},{
ageThisYear:function(){
returnnew
Date().getFullYear()-
this
.birthday.getFullYear()
},
getBirthday:function(){
return""
+this
.birthday.getFullYear()+
"-"
+(this
.birthday.getMonth()+1
)+
"-"
+this
.birthday.getDate();
}
});
//===============updaterWidget===============[code]
makeAgeUpdater=function(contact){
var
updater=$("#update"
)
//cleartheoldupdatecontentandaddthecontact'sbday
updater.html(""
)
.append(contact.name+"'sbirthday"
);
//createaninputelement
$('<input/>'
)
//setthecontactsbirthdayasval
.val(contact.attr("birthday"
))
//whentheinputchanges,updatethecontactwiththevalue
.change(function(){
contact.update({
'birthday'
:this
.value
})
})
//addtheinputtotheupdater
.appendTo(updater)
};
//===============Listenforupdates===============[code]
Contact.bind("updated"
,function(ev,contact){
//usethelisttogettheinstancefromtheelement
contact.elements($('#contacts'
))
.html(contact.name+""
+contact.ageThisYear()+
"<a>Show</a>"
);
});
//===============DrawoutContacts===============[code]
Contact.findAll({},function(contacts){
var
contactsEl=$('#contacts'
),
html=[],
contact;
//collectcontacthtml
for
(var
i=0
;i<contacts.length;i++){
contact=contacts[i]
html.push("<liclass='contact"
,
contact.identity(),//addtheidentitytotheclassNamemanually
"'>"
,
contact.name+""
+contact.ageThisYear()+
"<a>Show</a>"
,
"</li>"
)
}
//insertcontactshtml
contactsEl.html(html.join(""
))
contactsEl.delegate("li"
,"click"
,function(){
//usethecontactslisttogetthe
//contactfromtheclickedelement
var
contact=contacts.get(this
)[0
]
makeAgeUpdater(contact);
});
});
})
jQuery.Model.List.Cookieclass
plugin:jquery/model/list/cookiedownload:
jQuery.Model.List.Cookie
test:
qunit.html
Providesastore-ablelistofmodelinstances.Thefollowingretrievesandsavesalistofcontacts:
var[code]contacts=new
Contact.List([]).retrieve("contacts"
);
//addeachcontacttothepage[code]
contacts.each(function(){
addContact(this
);
});
//whenanewcookieiscrated[code]
$("#contact"
).submit(function(ev){
ev.preventDefault();
var
data=$(this
).formParams();
//givesitarandomid
data.id=+new
Date();
var
contact=new
Contact(data);
//addittothelistofcontacts
contacts.push(contact);
//storethecurrentlist
contacts.store("contacts"
);
//showthecontact
addContact(contact);
})
Youcanseethisinactioninthefollowingdemo.Createacontact,thenrefreshthepage.
Demo
HTML
<h2>[code]CreateAContact</h2>
<formaction=""id="contact">[code]
<label>
Name</label>
<inputname="name"type="text"><br>
<label>
Birthday</label>
<inputname="birthday"value="1982-10-20"type="text">
(mustbelike1982-10-20)<br>
<inputvalue="Create"type="submit">
</form>[code]
<h2>[code]ListofContacts</h2>
<divid="contacts"></div>
Source
steal('jquery/model'
,
'jquery/model/list/cookie'
,
'jquery/dom/form_params'
).then(function(){
$.Model("Contact"
,{
attributes:{
birthday:'date'
},
convert:{
date:function(raw){
if
(typeof
raw=='string'
){
var
matches=raw.match(/(\d+)-(\d+)-(\d+)/
)
returnnew
Date(+matches[1
],
(+matches[2
])-1
,
+matches[3
])
}elseif
(rawinstanceof
Date){
return
raw;
}
}
}
},{
ageThisYear:function(){
returnnew
Date().getFullYear()-
this
.birthday.getFullYear()
},
getBirthday:function(){
return""
+this
.birthday.getFullYear()+
"-"
+(this
.birthday.getMonth()+1
)+
"-"
+this
.birthday.getDate();
}
});
//Createacontactlist[code]
$.Model.List.Cookie("Contact.List"
);
//Ahelperfunctionforaddingacontacttothepage[code]
var[code]addContact=function(contact){
var
li=$('<li>'
)
.model(contact)
.html(contact.name+""
+contact.ageThisYear())
.appendTo($("#contacts"
));
}
$(function(){
//pullsavedcontactsintothislist
var
contacts=new
Contact.List([]).retrieve("contacts"
);
//addeachcontacttothepage
contacts.each(function(){
addContact(this
);
});
//whenanewcookieiscrated
$("#contact"
).submit(function(ev){
ev.preventDefault();
var
data=$(this
).formParams();
//givesitarandomid
data.id=+new
Date();
var
contact=new
Contact(data);
//addittothelistofcontacts
contacts.push(contact);
//storethecurrentlist
contacts.store("contacts"
);
//showthecontact
addContact(contact);
})
})
})
jQuery.Model.List.Cookie.prototype.retrievefunction
Deserializesalistofinstancesinthecookiewiththeprovidedname
API
model.list.cookie.retrieve(name)->jQuery.Model
name
{String}
thenameofthecookietouse.
returns
{jQuery.Model}
returnsthismodelinstance.
jQuery.Model.List.Cookie.prototype.storefunction
Serializesandsavesthislistofmodelinstancestothecookieinname.
API
model.list.cookie.store(name)->jQuery.Model
name
{String}
thenameofthecookie
returns
{jQuery.Model}
returnsthismodelinstance.
jQuery.Model.List.Localclass
plugin:jquery/model/list/localdownload:
jQuery.Model.List.Local
Worksexactlythesameas
jQuery.Model.List.Cookieexceptusesalocalstoreinsteadofcookies.
jQuery.Model.List.prototype.bindfunction
Listensforaneventsonthislist.Theonlyusefuleventsare:
.add-whennewitemsareadded.update-whenanitemisupdated.remove-whenitemsareremovedfromthelist(typicallybecausetheyaredestroyed).
Listenforitemsbeingadded
list.bind('add'
,function(ev,newItems){
})
Listenforitemsbeingremoved
list.bind('remove'
,function(ev,removedItems){
})
Listenforanitembeingupdated
list.bind('update'
,function(ev,updatedItem){
})
API
model.list.bind()->undefined
returns
{undefined}
jQuery.Model.List.prototype.destroyfunction
Destroysallitemsinthislist.ThiswillusetheList's
staticdestroymethod.
list.destroy(function(destroyedItems){
//success
},function(){
//error
});
API
model.list.destroy(success,error)->undefined
success
{Function}
ahandlercalledbackwiththedestroyeditems.Theoriginallistwillbeemptied.
error
{Function}
ahandlercalledbackwhenthedestroywasunsuccessful.
returns
{undefined}
jQuery.Model.List.prototype.eachfunction
Iteratesthroughthelistofmodelinstances,callingthecallbackfunctiononeachiteration.
list.each(function(indexInList,modelOfList){
...
});
API
model.list.each(callback)
callback
{Function}
Thefunctionthatwillbeexecutedoneveryobject.
jQuery.Model.List.prototype.elementsfunction
Returnselementsthatrepresentthislist.Forthistowork,yourelement'sshouldusthe
identityfunctionintheirclassname.Example:
<divclass='todo<%=todo.identity()%>'
>...</div>
Thisalsoworksifyouhookedupthemodel:
<div<%=todo%>>...</div>
Typically,you'llusethisasaresponsetoaModelEvent:
"{Todo}destroyed"[code]:function(Todo,event,todo){
todo.elements(this
.element).remove();
}
API
model.list.elements(context)->jQuery
context
{String|jQuery|element}
Ifprovided,onlyelementsinsidethiselementthatrepresentthismodelwillbereturned.
returns
{jQuery}
ReturnsajQuerywrappednodelistofelementsthathavethesemodelinstancesidentitiesintheirclassnames.
jQuery.Model.List.prototype.findAllfunction
Findsitemsandaddsthemtothislist.Thisuses
jQuery.Model.static.findAlltofinditemswiththeparamspassed.
API
model.list.findAll(params,success,error)->undefined
params
{Object}
optionstorefindthereturneditems
success
{Function}
calledwiththelist
error
{Object}
returns
{undefined}
jQuery.Model.List.prototype.getfunction
GetsalistofelementsbyIDorelement.
Tofetchbyid:
var[code]match=list.get(23
);
ortofetchbyelement:
var[code]match=list.get($('#content'
)[0
])
API
model.list.get(args)->undefined
args
{Object}
elementsoridstoretrieve.
jQuery.Model.List.prototype.grepfunction
Findstheinstancesofthelistwhichsatisfyacallbackfilterfunction.Theoriginalarrayisnotaffected.
var[code]matchedList=list.grep(function(instanceInList,indexInArray){
return
instanceInList.date<new
Date();
});
API
model.list.grep(callback,args)->undefined
callback
{Function}
thefunctiontocallback.ThisfunctionhasthesamecallpatternaswhatjQuery.grepprovides.
args
{Object}
returns
{undefined}
jQuery.Model.List.prototype.indexOffunction
Findstheindexoftheiteminthelist.Returns-1ifnotfound.
list.indexOf(item)
API
model.list.indexOf()
jQuery.Model.List.prototype.mapfunction
Iteratesthroughthelistofmodelinstances,callingthecallbackfunctiononeachiteration.
list.map(function(modelOfList,indexInList){
...
});
API
model.list.map(callback)
callback
{Function}
Thefunctiontoprocesseachitemagainst.
jQuery.Model.List.prototype.matchfunction
Returnsalistofallinstanceswho'spropertymatchesthegivenvalue.
list.match('candy'
,'snickers'
)
API
model.list.match(property,value)->undefined
property
{String}
thepropertytomatch
value
{Object}
thevaluethepropertymustequal
returns
{undefined}
jQuery.Model.List.prototype.pushfunction
Addsaninstanceorinstancestothelist
list.push(new
Recipe({id:5
,name:"Water"
}))
API
model.list.push(The)->Number
The
{args{Object}
instance(s)topushontothelist.
returns
{Number}
Thenumberofelementsinthelistafterthenewelementwaspushedin.
jQuery.Model.List.prototype.removefunction
Removesinstancesfromthislistbyidorbyanelement.
Toremovebyid:
var[code]match=list.remove(23
);
ortoremovebyelement:
var[code]match=list.remove($('#content'
)[0
])
API
model.list.remove(args)->undefined
args
{Object}
elementsoridstoremove.
jQuery.Model.List.prototype.reversefunction
Reversethelistinplace
list.reverse()
API
model.list.reverse()
jQuery.Model.List.prototype.shiftfunction
Removesthefirstinstanceofthelist,andreturnsthatinstance.
list.shift()
API
model.list.shift()
jQuery.Model.List.prototype.slicefunction
Theslicemethodselectsapartofanarray,andreturnsanotherinstanceofthismodellist'sclass.
list.slice(start,end)
API
model.list.slice(start,end)->undefined
start
{Number}
thestartindextoselect
end
{Number}
thelastindextoselect
returns
{undefined}
jQuery.Model.List.prototype.sortfunction
Sortstheinstancesinthelist.
list.sort(sortfunc)
API
model.list.sort()
jQuery.Model.List.prototype.splicefunction
Thesplicemethodaddsand/orremovesinstancesto/fromthelist,andreturnstheremovedinstance(s).
list.splice(index,howmany)
API
model.list.splice()
jQuery.Model.List.prototype.unbindfunction
Unbindsaneventonthislist.Oncealleventsareunbound,unbindstopslisteningtoallelementsinthecollection.
list.unbind("update"
)//unbindsallupdateevents
API
model.list.unbind()->undefined
returns
{undefined}
jQuery.Model.List.prototype.unshiftfunction
Addsanewinstancetothebeginningofanarray,andreturnsthenewlength.
list.unshift(element1,element2,...)
API
model.list.unshift()
jQuery.Model.List.prototype.updatefunction
Updatesitemsinthelistwithattributes.Thismakesarequestusingthelistclass's
staticupdate.
list.update(function(updatedItems){
//success
},function(){
//error
});
API
model.list.update(attrs,success,error)->undefined
attrs
{Object}
attributestoupdatethelistwith.
success
{Function}
ahandlercalledbackwiththeupdateditems.
error
{Function}
ahandlercalledbackwhentheupdatewasunsuccessful.
returns
{undefined}
jQuery.Model.List.static.destroyfunction
Destroyisusedtoremoveasetofmodelinstancesfromtheserver.Byimplementingdestroyalongwiththerestofthe[jquery.model.servicesserviceapi],yourmodelsprovideanabstractserviceAPI.
Youcanimplementdestroywithastringlike:
$.Model.List("Thing"
,{
destroy:"POST/thing/destroy/"
})
Oryoucanimplementdestroymanuallylike:
$.Model.List("Thing"
,{
destroy:function(ids,success,error){
return
$.ajax({
url:"/thing/destroy/"
,
data:ids,
success:success,
error:error,
type:"POST"
});
}
})
Thenyoudeletemodelsbycallingthe
prototypedeletemethod.
listInstance.destroy();
Bydefault,therequestwillPOSTanarrayofidstobedeletedinthebodyoftheAjaxrequest.
{
ids:[5
,10
,20
]
}
API
$.Model.List.destroy(ids,success,error)
ids
{Array}
theidsoftheinstancesyouwantdestroyed
success
{Function}
thecallbackfunction
error
{Function}
afunctiontocallbackifsomethinggoeswrong.
jQuery.Model.List.static.updatefunction
Updateisusedtoupdateasetofmodelinstancesontheserver.Byimplementingupdatealongwiththerestofthe[jquery.model.servicesserviceapi],yourmodelsprovideanabstractAPIforservices.
Theeasistwaytoimplementupdateistojustgiveittheurltoputdatato:
$.Model.List("Recipe"
,{
update:"PUT/thing/update/"
},{})
Oryoucanimplementupdatemanuallylike:
$.Model.List("Thing"
,{
update:function(ids,attrs,success,error){
return
$.ajax({
url:"/thing/update/"
,
success:success,
type:"PUT"
,
data:{ids:ids,attrs:attrs}
error:error
});
}
})
Thenyouupdatemodelsbycallingthe
prototypeupdatemethod.
listInstance.update({name:"Food"
})
Bydefault,therequestwillPUTanarrayofidstobeupdatedandthechangedattributesofthemodelinstancesinthebodyoftheAjaxrequest.
{
ids:[5
,10
,20
],
attrs:{
name:"Food"
}
}
Yourservershouldsendbackanobjectwithanynewattributesthemodelshouldhave.Forexampleifyourserverudpatesthe"updatedAt"property,itshouldsendbacksomethinglike:
//PUT/recipes/4,25,20{name:"Food"}->[code]
{
updatedAt:"10-20-2011"
}
API
$.Model.List.update(ids,attrs,success,error)
ids
{Array}
theidsofthemodelinstance
attrs
{Object}
Attributesonthemodelinstance
success
{Function}
thecallbackfunction.Itoptionallyacceptsanobjectofattribute/valuepairsofpropertychangestheclientdoesn'talreadyknowabout.Forexample,whenyouupdateanameproperty,theservermightupdateotherpropertiesaswell(suchasupdatedAt).
Theservershouldsendthesepropertiesastheresponsetoupdates.Passingthemtosuccesswillupdatethemodelinstanceswiththeseproperties.
error
{Function}
afunctiontocallbackifsomethinggoeswrong.
相关文章推荐
- jquery 中$.post获取MVC Controller中JsonResult返回包含LIst<Model>类型的子List<Model>的高级使用方法
- jquery 中$.post获取MVC Controller中JsonResult返回包含LIst<Model>类型的子List<Model>的高级使用方法
- MVC使用jQuery从视图向控制器传递Model的2种方法
- Html5+css3+angularjs+jquery+webAPi 开发手机web(一)
- jQuery验证控件jquery.validate.js使用说明+中文API
- jQuery validate api(转)
- JQuery- AJAX相关的API
- jQuery常用API
- JQuery的Flexigrid的API使用
- 【WEBAPI】关于WEBAPI无法获取数据的问题之一(Issues while making a POST to a Web API from JQuery)
- jQuery EasyUI API 中文文档 - ComboBox组合框
- jQuery验证控件jquery.validate.js使用说明+中文API
- paip.元数据驱动的转换-读取文件行到个list理念 uapi java php python总结
- jQuery EasyUI API 中文文档 - TimeSpinner时间微调器
- jQuery验证控件jquery.validate.js使用说明+中文API
- jQuery全屏滚动插件FullPage.js中文帮助文档API
- JQuery上传插件Uploadify API详解
- 转载:The Essential List of JavaScript, jQuery, HTML & CSS Books to Make You a Better Web Developer
- jQuery EasyUI API 中文文档 - MenuButton菜单按钮使用介绍
- jQuery EasyUI API 中文文档 - Tabs标签页/选项卡