您的位置:首页 > Web前端 > JQuery

jquery.model.list-api

2013-06-10 17:42 204 查看

jQuery.Model.Listclass

plugin:jquery/model/list

download:
jQuery.Model.List

test:qunit.html

Source

Model.Listsmanagealists(orarrays)ofmodelinstances.Similarto
$.Model,theyareusedto:

createeventswhenalistchanges
makeAjaxrequestsonmultipleinstances
addhelperfunctionformultipleinstances(ACLs)

Thetodoappdemonstratesusinga$.Controllertoimplementaninterfacefora$.Model.List.

CreatingAListClass

Createa`$.Model.List
classfora$.Modellike:

$.Model(
'Todo'
)

$.Model.List(
'Todo.List'
,{

//staticproperties

},{

//prototypeproperties

})


Thiscreatesa
Todo.List
classforthe
Todo
class.Thiscreatessomeniftymagicthatwewillseesoon.

static
propertiesaretypicallyusedtodescribehowalistmakesrequests.
prototype
propertiesarehelperfunctionsthatoperateonaninstanceofalist.

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(){

return
this
.grep(
function(todo){

return
todo.acl.indexOf(
"d"
)!=
0

}).length==
this
.length

}

})


canDelete
getsalistofalltodosthathavedintheiracl.Ifalltodoshave
d,then
canDelete
returnstrue.

GetaListInstance

Youcancreateamodellistinstancebyusing
newTodo.List(instances)
like:

var[code]todos=
new
Todo.List([

new
Todo({id:
1
,name:...}),

new
Todo({id:
2
,name:...}),

]);


Andcall
canDelete
onitlike:

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
.todo
elementsaredeletable:

//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(){

return
this
.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

Use
bind
(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

Storeandretrievemultipleinstances
FastHTMLinserts

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+)/
)

return
new
Date(+matches[
1
],

(+matches[
2
])-
1
,

+matches[
3
])

}
else
if
(raw
instanceof
Date){

return
raw;

}

}

},

findAll:
"/recipes.json"
,

update:
"/recipes/{id}.json"

},{

ageThisYear:
function(){

return
new
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/cookie

download:
jQuery.Model.List.Cookie

test:
qunit.html

Source

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+)/
)

return
new
Date(+matches[
1
],

(+matches[
2
])-
1
,

+matches[
3
])

}
else
if
(raw
instanceof
Date){

return
raw;

}

}

}

},{

ageThisYear:
function(){

return
new
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

Source

Deserializesalistofinstancesinthecookiewiththeprovidedname

API

model.list.cookie.retrieve(name)->jQuery.Model


name
{String}


thenameofthecookietouse.

returns
{jQuery.Model}


returnsthismodelinstance.

jQuery.Model.List.Cookie.prototype.storefunction

Source

Serializesandsavesthislistofmodelinstancestothecookieinname.

API

model.list.cookie.store(name)->jQuery.Model


name
{String}


thenameofthecookie

returns
{jQuery.Model}


returnsthismodelinstance.

jQuery.Model.List.Localclass

plugin:jquery/model/list/local

download:
jQuery.Model.List.Local

Source

Worksexactlythesameas
jQuery.Model.List.Cookieexceptusesalocalstoreinsteadofcookies.

jQuery.Model.List.prototype.bindfunction

Source

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

Source

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

Source

Iteratesthroughthelistofmodelinstances,callingthecallbackfunctiononeachiteration.

list.each(
function(indexInList,modelOfList){

...

});


API

model.list.each(callback)


callback
{Function}


Thefunctionthatwillbeexecutedoneveryobject.

jQuery.Model.List.prototype.elementsfunction

Source

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

Source

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

Source

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

Source

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

Source

Findstheindexoftheiteminthelist.Returns-1ifnotfound.

list.indexOf(item)


API

model.list.indexOf()


jQuery.Model.List.prototype.mapfunction

Source

Iteratesthroughthelistofmodelinstances,callingthecallbackfunctiononeachiteration.

list.map(
function(modelOfList,indexInList){

...

});


API

model.list.map(callback)


callback
{Function}


Thefunctiontoprocesseachitemagainst.

jQuery.Model.List.prototype.matchfunction

Source

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

Source

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

Source

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

Source

Reversethelistinplace

list.reverse()


API

model.list.reverse()


jQuery.Model.List.prototype.shiftfunction

Source

Removesthefirstinstanceofthelist,andreturnsthatinstance.

list.shift()


API

model.list.shift()


jQuery.Model.List.prototype.slicefunction

Source

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

Source

Sortstheinstancesinthelist.

list.sort(sortfunc)


API

model.list.sort()


jQuery.Model.List.prototype.splicefunction

Source

Thesplicemethodaddsand/orremovesinstancesto/fromthelist,andreturnstheremovedinstance(s).

list.splice(index,howmany)


API

model.list.splice()


jQuery.Model.List.prototype.unbindfunction

Source

Unbindsaneventonthislist.Oncealleventsareunbound,unbindstopslisteningtoallelementsinthecollection.

list.unbind(
"update"
)
//unbindsallupdateevents


API

model.list.unbind()->undefined


returns
{undefined}


jQuery.Model.List.prototype.unshiftfunction

Source

Addsanewinstancetothebeginningofanarray,andreturnsthenewlength.

list.unshift(element1,element2,...)


API

model.list.unshift()


jQuery.Model.List.prototype.updatefunction

Source

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

Source

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

Source

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: